user13240529
user13240529

Reputation: 23

Dart Function syntax

I am very new to Dart and Flutter. I have come across a programming syntax while looking at responsive_builder.dart class as follows:

final Widget Function(BuildContext buildContext, SizingInformation sizingInformation) builder;

I searched about a lot regarding Function() syntax but somehow did not find anything. Similarly, I tried on https://dartpad.dev as below:

class Dog{
   String Function(String j, String u) functionName;
}

And dart pad did not complain about it. Please help me understand what is Function() type syntax.

Upvotes: 2

Views: 544

Answers (2)

wcyankees424
wcyankees424

Reputation: 2664

I Believe this is what you are asking take your example modified slightly function for example

String Function(BuildContext context, int index) functionName;

Function is just letting dart know that you are declaring a function you can also declare a function like this.

String functionName(BuildContext context, int index) {}

String in this example is the return type of the function while BuildContext and int are input types for the function finally context and index are the variable names to be used inside functionName.

For a more detailed explanation here is Dart Programming Tutorial you might have already read this though

Upvotes: 0

pedro pimont
pedro pimont

Reputation: 3094

    class Dog{
   String Function(String j, String u) functionName;
}

In this case there's nothing wrong with this syntax. You're only declaring a variable functionName of type Function that returns a String and takes two arguments String j, String u without properly initializing it.

You could do something like:

void main() async {

  Dog newDog = Dog(functionName: (String j, String u) => j + ' ' + u );

  print(newDog.functionName('Hello', 'World'));

}

 class Dog{
   final String Function(String j, String u) functionName;
   Dog({this.functionName});
}

output:

Hello World

What I essentially did here was to define the functionName Function on the Dog class and then pass a Anonymous Function of the same type to its Constructor when initializing a new Dog object called newDog.

I can then call newDog.functionName(String arg1, String arg2). This will return a run the Anonymous Function we passed earlier to the newDog object Constructor and return a new concatenated string.

Upvotes: 1

Related Questions