在Dart中,Function()和Function之间有什么区别?

14

在类中声明函数成员时,我们可以做两件事;

Function first;
Function() second;

它们之间有什么区别?

2个回答

20
  • Function 代表任何函数:
void function() {}
int anotherFunction(int positional, {String named}) {}


Function example = function; // works
example = anotherFunction; // works too
  • Function() 表示一个没有参数的函数:
void function() {}
int anotherFunction(int positional, {String named}) {}


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

一种 Function() 的变体可能是:
void Function() example;

同样地,我们可以为我们的函数指定参数:
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

0

实际示例,

我们有一个名为callMe()的方法,它将由RaisedButton调用。

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

RaisedButton 代码:

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

如果 callMe() 方法有参数,则它将无法正常工作,因为需要从具有参数的函数中调用 Function(param)。
void callMe(String title) {
        print('Call Me');
      }

带有功能代码的RaisedButton:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接