【问题标题】:How to return the function in a closure in dart?如何在飞镖的闭包中返回函数?
【发布时间】:2021-08-12 18:35:28
【问题描述】:

例如:

Future<int> _test1() async {
  return Future.delayed(Duration(seconds: 1)).then((value) {
    return 1;
  });
}

void _onTapButton() async {
  await _test1().then((value) {
    print('a');
    if (value == 1) {
      print('return');
      return;
    }
  });

  print('b');
}

当我打电话给_onTapButton 时,控制台打印 a return b 不是 a return.

也就是说_test1().then中的return没有返回函数_onTapButton

有什么方法可以在_test1().then 中返回函数_onTapButton

【问题讨论】:

    标签: flutter dart async-await future


    【解决方案1】:

    在您的代码中,then 部分是一个回调,将在您的未来完成时执行,return 是指在此回调的范围内,而不是您的 _onTapButton 函数。

    如果你想等待未来,如果结果为1,打印return并从_onTapButton返回,你可以试试这个:

    void _onTapButton() async {
       final value = await _test1();
       print('a');
       if (value == 1) {
          print('return');
          return;
       }
       print('b');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      • 2022-07-09
      • 2020-11-28
      • 2019-06-25
      • 1970-01-01
      相关资源
      最近更新 更多