在Flutter中如何将回调转换为未来?

ajsxfq5m  于 2022-11-30  发布在  Flutter
关注(0)|答案(2)|浏览(138)

在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.
slwdgvem

slwdgvem1#

假设我们有一个普通的方法,它只返回一个如下的值:

int returnValueMethod() {
 return 42;
}

我们可以像这样直接将它赋值给Future.value(),使它成为Future

Future.value(returnValueMethod());
wi3ka0sx

wi3ka0sx2#

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.

相关问题