Search code examples
flutterdartfuture

How do you convert a callback to a future in Flutter?


In Javascript you can convert a callback to a promise with:

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

Is that possible in Flutter?

Example:

// 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.

Solution

  • Found the answer from 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;
    }
    

    So to accommodate the example listed above:

    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.