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

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

文章目录

一、Future 简介

二、Future.then 使用

三、Future 异常捕获

四、Dart 练习网站

五、async、await 关键字

六、whenComplete 方法

七、timeout 方法

八、相关资源





一、Future 简介


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


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



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



Future 有两种状态 :


① 执行中 , Pending 状态 ;

② 执行结果 , Complete 状态 ;





二、Future.then 使用


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


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


Future<String> testFuture() {
  return Future.value('success');
}
main() {
  testFuture().then((s) {
    print(s);
  });
}


Future 的 then 方法原型如下 :


 

/// 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


Future<String> testFuture() {
  return Future.value('success');
}
main() {
  testFuture().then((s) {
    print(s);
  }, onError: (e) {
    print('onError:');
    print(e);
  });
}


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


Future<String> testFuture() {
  return Future.value('success');
}
main() {
  testFuture().then((s) {
    print(s);
  }).catchError((e) {
    print('catchError:');
    print(e);
  });
}



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



目录
相关文章
|
Dart 开发者
【Flutter】Future 异步编程 ( 简介 | then 方法 | 异常捕获 | async、await 关键字 | whenComplete 方法 | timeout 方法 )(二)
【Flutter】Future 异步编程 ( 简介 | then 方法 | 异常捕获 | async、await 关键字 | whenComplete 方法 | timeout 方法 )(二)
489 0
|
4月前
|
监控 Dart 安全
创建一个Dart应用,监控局域网上网记录的软件:Flutter框架的应用
在当今数字时代,网络安全变得愈发重要。为了监控局域网上的上网记录,我们可以借助Flutter框架创建一个强大的Dart应用。在这篇文章中,我们将深入讨论如何使用Flutter框架开发这样一个监控局域网上网记录的软件,并提供一些实用的代码示例。
281 1
|
7月前
|
Dart Android开发 UED
带你读《深入浅出Dart》二十七、Flutter路由管理
带你读《深入浅出Dart》二十七、Flutter路由管理
|
12天前
|
Dart 前端开发 开发者
【Flutter前端技术开发专栏】Flutter Dart语言基础语法解析
【4月更文挑战第30天】Dart是Google为Flutter框架打造的高效编程语言,具有易学性、接口、混入、抽象类等特性。本文概述了Dart的基础语法,包括静态类型(如int、String)、控制流程(条件、循环)、函数、面向对象(类与对象)和异常处理。此外,还介绍了库导入与模块使用,帮助开发者快速入门Flutter开发。通过学习Dart,开发者能创建高性能的应用。
【Flutter前端技术开发专栏】Flutter Dart语言基础语法解析
|
13天前
|
Dart 测试技术 UED
Dart 和 Flutter 错误处理指南 | 最佳实践全解析
深入探索 Dart 和 Flutter 中的错误处理技术,从编译时错误到运行时异常,带你学习如何优雅地处理应用程序中的各种意外情况。了解最佳实践,让你的应用程序稳如磐石,用户体验持续优化!
Dart 和 Flutter 错误处理指南 | 最佳实践全解析
|
16天前
|
存储 缓存 开发框架
Flutter的网络请求:使用Dart进行HTTP请求的技术详解
【4月更文挑战第26天】了解Flutter网络请求,本文详述使用Dart进行HTTP请求
|
16天前
|
开发框架 Dart Java
Flutter的核心:Dart语言基础——语法与特性深度解析
【4月更文挑战第26天】Flutter框架背后的Dart语言,以其简洁的语法和独特特性深受开发者喜爱。本文深入解析Dart的语法与特性,如类型推导、动态静态类型系统、统一的类接口、访问权限控制以及并发编程支持。了解并掌握Dart,能助开发者更高效地利用Flutter构建高性能移动应用。
|
3月前
|
Dart JavaScript
Flutter - Dart 基础(数据类型)
【2月更文挑战第3天】
71 1
|
3月前
|
Dart JavaScript 安全
|
3月前
|
Dart Shell 开发工具
解决windows安装Flutter时出现Unknown operating system. Cannot install Dart SDK.问题
解决windows安装Flutter时出现Unknown operating system. Cannot install Dart SDK.问题