14.关于Dart中的Future你掌握的够吗?

2,569 阅读1分钟

目录传送门:《Flutter快速上手指南》先导篇

《异步-async和await》 小节中,提到过一个异步函数,会返回一个 Future 对象,它持有了异步函数的返回结果。

本篇文章,就来认识一下 Future 吧。

认识 Future

Future 是在未来某个时间获得想要对象的一种手段。

以上是 Future 的定义。

简单来说,就是我们能够通过它在某个时间点获得异步任务中返回的值。

实际上,就是给 Future 设置回调函数,当异步任务执行完成后,会调用回调函数。

Future<T> login = new Future<T>(() {
                      ...
                      return t;
                    });
login.then((t){
    //..
})

当异步的 login 任务执行完成后,回调用 then() 中的回调函数。

Future 的常用函数

  • Future.then()

    任务执行完成会进入这里,能够获得返回的执行结果。

  • Future.catchError()

    有任务执行失败,可以在这里捕获异常。

  • Future.whenComplete()

    当任务停止时,最后会执行这里。

  • Future.wait()

    可以等待多个异步任务执行完成后,再调用 then()

    只有有一个执行失败,就会进入 catchError()

  • Future.delayed()

    延迟执行一个延时任务。

这是一个例子:

Future.wait([
  // 2秒后返回结果
  Future.delayed(new Duration(seconds: 2), () {
    return "hello";
  }),
  // 4秒后返回结果
  Future.delayed(new Duration(seconds: 4), () {
    return " world";
  })
]).then((results) {
  //执行成功会走到这里
  print(results[0]+results[1]);
}).catchError((e){
  //执行失败会走到这里
  print(e);
}).whenComplete((){
  //无论成功或失败都会走到这里
});;


目录传送门:《Flutter快速上手指南》先导篇

如何找到我?

传送门:CoorChice 的主页

传送门:CoorChice 的 Github