【发布时间】:2020-06-26 02:08:18
【问题描述】:
在类中声明一个函数成员时,我们可以同时做这两个;
Function first;
Function() second;
它们有什么区别?
【问题讨论】:
在类中声明一个函数成员时,我们可以同时做这两个;
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() 方法有参数,那么它将不能作为需要从有参数的函数调用的函数(参数)工作
void callMe(String title) {
print('Call Me');
}
带有功能代码的RaisedButton:
RaisedButton(
onPressed: () {
callMe('sample');
},
child: Text('Pressed Me '),
),
【讨论】: