【问题标题】:Function as parameter (DART)作为参数的函数 (DART)
【发布时间】:2020-02-19 18:47:51
【问题描述】:

我试图了解 dart 如何使用函数作为参数。我写了这段代码……

typedef Future<String> myFunction();

void main() {
  A a = A();
  a.f1(a._f1);
}

class A {
  f1(myFunction func) async {
    String x = await _f1;
    print(x);
  }

  Future<String> _f1() {
    Future.delayed(Duration(seconds: 3)).then((f) {
      return "test";
    });
  }
} 

我需要函数 f1 返回“test”,但我有这个错误:“Future Function()”类型的值不能分配给“String”类型的变量

如果我将 String x = await _f1 更改为 Future x = await _f1 我还有另一个错误.. 我尝试了很多 组合,他们都失败了。

有人可以修复我的代码吗?谢谢你。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    问题出在这一行:

    String x = await _f1;
    

    方法的参数是func,所以这里直接引用_f1方法而不是参数。此外,您只是直接引用该方法,而不是调用该方法。本质上,您正在尝试将 Function 分配给需要 String 的变量,这就是错误消息试图告诉您的内容。

    你需要引用参数,然后你需要调用它。

    String x = await func();
    

    顺便说一句,您的_f1 方法当前正在返回null。这是因为你从 then 中的方法返回了一个值,但你没有返回任何东西给 _f1 本身,这使得 Dart 默认返回 null。您必须返回未来本身:

    Future<String> _f1() {
      return Future.delayed(Duration(seconds: 3)).then((f) {
        return "test";
      });
    }
    
    

    或者你需要切换到async/await语法(我个人推荐):

    Future<String> _f1() async {
      await Future.delayed(Duration(seconds: 3));
      return 'test';
    }
    

    【讨论】:

      【解决方案2】:

      要执行一个函数,你需要在它的名字后面加上括号( arguments )。函数是变量还是预定义的(常量)都没有关系。

      请查看以下示例:

      示例 1.

      Future<int> add(int a, int b) async {
        return Future.delayed(Duration(seconds: 2)).then((f) {
          return a + b;
        });
      }
      
      Future<int> test(Future<int> Function(int a, int b) func) async {
        return await func(3, 2);
      }
      
      void main() {
        test(add)
          .then(print); /// will return result of 3+2 after 2 seconds
      }
      

      Run this code

      示例 2。

      String Function(String, String) mergeFunction = (String a, String b) {
        return a + b;
      };
      
      void main() {
        print(mergeFunction('Hello ', 'world'));
      }
      

      Run this code

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2017-09-06
        • 2020-08-01
        相关资源
        最近更新 更多