Home > other >  How do you convert a callback to a future in Flutter?
How do you convert a callback to a future in Flutter?

Time:11-26

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.

CodePudding user response:

saying that we have a normal method that return just a value like this:

int returnValueMethod() {
 return 42;
}

we can make it a Future by assigning it directly to Future.value() like this:

Future.value(returnValueMethod());

CodePudding user response:

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.
  • Related