前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Flutter】Future 异步编程 ( 简介 | then 方法 | 异常捕获 | async、await 关键字 | whenComplete 方法 | timeout 方法 )

【Flutter】Future 异步编程 ( 简介 | then 方法 | 异常捕获 | async、await 关键字 | whenComplete 方法 | timeout 方法 )

作者头像
韩曙亮
发布2023-03-29 15:46:42
9380
发布2023-03-29 15:46:42
举报
文章被收录于专栏:韩曙亮的移动开发专栏

文章目录

一、Future 简介


Future 指的是在 将来 的 某个时刻 的 结果 , 可以是一个值 , 也可以是一个报错信息 ;

借助 Future 可以实现异步操作 ;

Future 是在 dart:async 包中的类 , 系统会默认导入该包中的类 , 直接使用即可 , 不需要刻意导入 ;

Future 有两种状态 :

  • ① 执行中 , Pending 状态 ;
  • ② 执行结果 , Complete 状态 ;

二、Future.then 使用


调用 then 方法 , 可以在该方法中 , 获取 Future 中的值 , 其类型是 Future 泛型中的类型 ;

调用 testFuture 方法后 , 调用 then 方法 , 可以获取 testFuture 方法返回的 String 字符串 , 就是 s 参数 , 打印该字符串 ;

代码语言:javascript
复制
Future<String> testFuture() {
  return Future.value('success');
}

main() {
  testFuture().then((s) {
    print(s);
  });
}

Future 的 then 方法原型如下 :

代码语言:javascript
复制
  /// Register callbacks to be called when this future completes.
  ///
  /// When this future completes with a value,
  /// the [onValue] callback will be called with that value.
  /// If this future is already completed, the callback will not be called
  /// immediately, but will be scheduled in a later microtask.
  ///
  /// If [onError] is provided, and this future completes with an error,
  /// the `onError` callback is called with that error and its stack trace.
  /// The `onError` callback must accept either one argument or two arguments
  /// where the latter is a [StackTrace].
  /// If `onError` accepts two arguments,
  /// it is called with both the error and the stack trace,
  /// otherwise it is called with just the error object.
  /// The `onError` callback must return a value or future that can be used
  /// to complete the returned future, so it must be something assignable to
  /// `FutureOr<R>`.
  ///
  /// Returns a new [Future]
  /// which is completed with the result of the call to `onValue`
  /// (if this future completes with a value)
  /// or to `onError` (if this future completes with an error).
  ///
  /// If the invoked callback throws,
  /// the returned future is completed with the thrown error
  /// and a stack trace for the error.
  /// In the case of `onError`,
  /// if the exception thrown is `identical` to the error argument to `onError`,
  /// the throw is considered a rethrow,
  /// and the original stack trace is used instead.
  ///
  /// If the callback returns a [Future],
  /// the future returned by `then` will be completed with
  /// the same result as the future returned by the callback.
  ///
  /// If [onError] is not given, and this future completes with an error,
  /// the error is forwarded directly to the returned future.
  ///
  /// In most cases, it is more readable to use [catchError] separately,
  /// possibly with a `test` parameter,
  /// instead of handling both value and error in a single [then] call.
  ///
  /// Note that futures don't delay reporting of errors until listeners are
  /// added. If the first `then` or `catchError` call happens
  /// after this future has completed with an error,
  /// then the error is reported as unhandled error.
  /// See the description on [Future].
  Future<R> then<R>(FutureOr<R> onValue(T value), {Function? onError});

then 方法的第一个参数 FutureOr<R> onValue(T value) 就是 Future 的 onValue 代表的值 , 类型是 Future 泛型类型 R ;

then 方法的第二个参数 {Function? onError} 是可选的 , 用于捕获异常的方法 ;

三、Future 异常捕获


方式一 : then 方法传入 onError 参数 ;

在执行 返回值是 Future 类型的 testFuture 方法时 , 在 then 方法中 , 第二个参数 onError

代码语言:javascript
复制
Future<String> testFuture() {
  return Future.value('success');
}

main() {
  testFuture().then((s) {
    print(s);
  }, onError: (e) {
    print('onError:');
    print(e);
  });
}

方式二 : 继续链式调用 , 在 then 方法后 , 继续调用 Future 的 catchError 方法 ;

代码语言:javascript
复制
Future<String> testFuture() {
  return Future.value('success');
}

main() {
  testFuture().then((s) {
    print(s);
  }).catchError((e) {
    print('catchError:');
    print(e);
  });
}

注意 : 上述两个方法只能二选其一 , 如果都设置了 , 那么只有 方式一 生效 , 方式二 会被覆盖 ;

四、Dart 练习网站


https://dartpad.dartlang.org/ 网站 , 练习 Dart 语言 ;

五、async、await 关键字


async 关键字一般用作 方法的后缀 , 被修饰的方法的 返回值必须是 Future 类型的 ;

方法执行时 , 以 同步的形式 执行到 await 关键字位置 , 然后 挂起 , 等待后续异步方法执行 ;

异步任务执行完毕后 , await 之后的代码开始执行 ;

六、whenComplete 方法


在 Future 执行快要结束时 , 如果想要执行一些任务 , 可以在链式调用时 , 调用 Future 的 whenComplete 方法 ;

该方法类似于 try … catch … finally 中的 finally 代码块 , 是必定执行的代码 , 即使出险错误 , 也会执行该代码 ;

代码语言:javascript
复制
Future<String> testFuture() {
  return Future.value('success');
}

main() {
  testFuture().then((s) {
    print(s);
  }).catchError((e) {
    print('catchError:');
    print(e);
  }).whenComplete(() {
    print('whenComplete');
  });
}

七、timeout 方法


有的异步操作可能需要很长时间完成 , 这里为异步操作指定一个超时时间 ;

在 Future 链式调用时 , 调用 timeout 方法 , 设置超时时间 ;

代码语言:javascript
复制
void main() {
  /// 异步操作中会延迟 3 秒 , 超时时间 2 秒 
  new Future.delayed(new Duration(seconds: 3), () {
    return 1;
  }).timeout(new Duration(seconds: 2)).then(print).catchError(print);
}

八、相关资源


参考资料 :

重要的专题 :

博客源码下载 :

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-08-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、Future 简介
  • 二、Future.then 使用
  • 三、Future 异常捕获
  • 四、Dart 练习网站
  • 五、async、await 关键字
  • 六、whenComplete 方法
  • 七、timeout 方法
  • 八、相关资源
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档