【问题标题】:How do you convert a callback to a future in Flutter?在 Flutter 中如何将回调转换为未来?
【发布时间】:2022-11-26 03:25:02
【问题描述】:

在 Javascript 中,您可以使用以下方法将回调转换为承诺:

function timeout(time){
   return new Promise(resolve=>{
      setTimeout(()=>{
         resolve('done with timeout');
      }, time)
   });
}

这在 Flutter 中可能吗?

例子:

// I'd like to use await syntax, so I make this return a future
Future<void> _doSomething() async {
    // I'm call a function I don't control that uses callbacks
    // I want to convert it to async/await syntax (Future)
    SchedulerBinding.instance.addPostFrameCallback((_) async {
        // I want to do stuff in here and have the return of
        // `_doSomething` await it
        await _doSomethingElse();
    });
}

await _doSomething();
// This will currently finish before _doSomethingElse does.

【问题讨论】:

  • 这没有意义。 Future 只是异步操作完成的通知。如果您的回调是同步的,则不需要通知您。如果它是异步的,它已经返回一个Future。你的最终目标是什么?如果您只是想延迟调用同步回调,只需将其包装在一个首先执行 await Future. delayed(...) 的异步函数中。
  • 回调和 Futures 是执行依赖于异步操作的代码的两种不同模式。这个问题涵盖了您正在使用仅提供回调语法的库的情况,您希望将其转换为异步/等待语法。为了清楚起见,我提供了一个示例。那有意义吗?

标签: flutter dart future


【解决方案1】:

说我们有一个正常的方法,它只返回一个像这样的值:

int returnValueMethod() {
 return 42;
}

我们可以通过将它直接分配给Future.value()来使其成为Future,如下所示:

Future.value(returnValueMethod());

【讨论】:

    【解决方案2】:

    this post找到了答案。

    Future time(int time) async {
        
      Completer c = new Completer();
      new Timer(new Duration(seconds: time), (){
        c.complete('done with time out');
      });
    
      return c.future;
    }
    

    因此,为了适应上面列出的示例:

    Future<void> _doSomething() async {
        Completer completer = new Completer();
        
        SchedulerBinding.instance.addPostFrameCallback((_) async {
            
            await _doSomethingElse();
            
            completer.complete();
        });
        return completer.future
    }
    
    await _doSomething();
    // This won't finish until _doSomethingElse does.
    

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2014-02-25
      • 2015-12-11
      • 2021-04-18
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多