如何解决 flutter(dart)中的 Future?

Mar*_*S82 8 dart flutter

我想编写一个函数,该函数会返回直到上传完成。如果可以的话,如果我还可以添加一个超时就好了。

 waitForUpload() async {
     uploader.result.listen((result) {
        // return waitForUpload
     }
 }
Run Code Online (Sandbox Code Playgroud)

我只是不知道如何用 dart 写这个。更清楚地说:在 JS 中,代码如下所示:

async waitForUpload() {
  return new Promise((resolve) => {
    uploader.result.listen((result) {
        resolve();
    });
  });
} 
Run Code Online (Sandbox Code Playgroud)

小智 9

使用 Completer 会更直接。

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)


Mar*_*S82 2

Stream.single实现我想要的行为。查看实现,您可以看到 在解决 future 的方法future._complete(result);内部被调用。listen