What is the difference between Function() and Function in dart?

Viewed 835

While declaring a Function member in a class we can do both;

Function first;
Function() second;

What is the difference between them?

2 Answers
  • Function represents any function:
void function() {}
int anotherFunction(int positional, {String named}) {}


Function example = function; // works
example = anotherFunction; // works too
  • Function() represents a function with no parameter:
void function() {}
int anotherFunction(int positional, {String named}) {}


Function() example = function; // works
example = anotherFunction; // doesn't compile. anotherFunction has parameters

A variant of Function() could be:

void Function() example;

Similarly, we can specify parameters for our function:

void function() {}
int anotherFunction(int positional, {String named}) {}

int Function(int, {String named}) example;

example = function; // Doesn't work, function doesn't match the type defined
example = anotherFunction; // works

Practical Example of it,

We have method callMe() which will be called by RaisedButton

 void callMe() {
    print('Call Me');
  }

RaisedButton Code:

RaisedButton(
        onPressed: callMe, // its working even if we called another method from here
        child: Text('Pressed Me '),
      ),

If callMe() method have param then it will not works as Function(param) required to be called from Function which have params

void callMe(String title) {
        print('Call Me');
      }

RaisedButton with Function Code:

RaisedButton(
        onPressed: () {
          callMe('sample'); 
        },
        child: Text('Pressed Me '),
      ),
Related