How to resolve a Future in flutter (dart)?

Viewed 1088

I want to write a functions which returns until an upload has been finished. If it is possible it would be good if I could also add a timeout.

 waitForUpload() async {
     uploader.result.listen((result) {
        // return waitForUpload
     }
 }

I just don't find how to write this in dart. To make it more clear: In JS the code would look like this:

async waitForUpload() {
  return new Promise((resolve) => {
    uploader.result.listen((result) {
        resolve();
    });
  });
} 
2 Answers

Using a Completer would be more straightforward.

Future time(int time) async {

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

  return c.future;
}

Stream.single implements the behavior I want. Looking at implementation, you can see future._complete(result); is called inside the listen method which resolves the future.

Related