【问题标题】:What is the difference between Function() and Function in dart?dart 中的 Function() 和 Function 有什么区别?
【发布时间】:2020-06-26 02:08:18
【问题描述】:

在类中声明一个函数成员时,我们可以同时做这两个;

Function first;
Function() second;

它们有什么区别?

【问题讨论】:

    标签: function flutter dart


    【解决方案1】:
    • 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
    

    【讨论】:

      【解决方案2】:

      它的实际例子,

      我们有方法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 '),
            ),
      

      【讨论】:

        猜你喜欢
        • 2012-07-12
        • 2017-12-05
        • 2015-03-08
        • 2012-02-18
        • 2012-10-18
        • 1970-01-01
        • 2019-05-02
        • 2021-09-13
        • 2015-08-10
        相关资源
        最近更新 更多