简体   繁体   English

dart中的Function()和Function有什么区别?

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

While declaring a Function member in a class we can do both;class 中声明 Function 成员时,我们可以同时做这两个;

Function first;
Function() second;

What is the difference between them?它们之间有什么区别?

  • Function represents any function: Function代表任何 function:
void function() {}
int anotherFunction(int positional, {String named}) {}


Function example = function; // works
example = anotherFunction; // works too
  • Function() represents a function with no parameter: Function()表示没有参数的 function:
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: Function()的变体可能是:

void Function() example;

Similarly, we can specify parameters for our function:同样,我们可以为我们的 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我们有方法callMe () 将被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如果callMe () 方法有参数,那么它将不能作为需要从具有参数的 Function 调用的 Function(param) 工作

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

RaisedButton with Function Code:带有 Function 代码的凸起按钮:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM