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

Kyl*_*enn 2 future dart flutter

在 Javascript 中,你可以使用以下方法将回调转换为 Promise:

function timeout(time){
   return new Promise(resolve=>{
      setTimeout(()=>{
         resolve('done with timeout');
      }, time)
   });
}
Run Code Online (Sandbox Code Playgroud)

在 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.
Run Code Online (Sandbox Code Playgroud)

Kyl*_*enn 8

从这篇文章中找到了答案。

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

  return c.future;
}
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)