在类中声明函数成员时,我们可以做两件事;
Function first;
Function() second;
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
实际示例,
我们有一个名为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 '),
),