【Flutter】Future 异步编程 ( 简介 | then 方法 | 异常捕获 | async、await 关键字 | whenComplete 方法 | timeout 方法 )
文章目錄
- 一、Future 簡(jiǎn)介
- 二、Future.then 使用
- 三、Future 異常捕獲
- 四、Dart 練習(xí)網(wǎng)站
- 五、async、await 關(guān)鍵字
- 六、whenComplete 方法
- 七、timeout 方法
- 八、相關(guān)資源
一、Future 簡(jiǎn)介
Future 指的是在 將來(lái) 的 某個(gè)時(shí)刻 的 結(jié)果 , 可以是一個(gè)值 , 也可以是一個(gè)報(bào)錯(cuò)信息 ;
借助 Future 可以實(shí)現(xiàn)異步操作 ;
Future 是在 dart:async 包中的類 , 系統(tǒng)會(huì)默認(rèn)導(dǎo)入該包中的類 , 直接使用即可 , 不需要刻意導(dǎo)入 ;
Future 有兩種狀態(tài) :
- ① 執(zhí)行中 , Pending 狀態(tài) ;
- ② 執(zhí)行結(jié)果 , Complete 狀態(tài) ;
二、Future.then 使用
調(diào)用 then 方法 , 可以在該方法中 , 獲取 Future 中的值 , 其類型是 Future 泛型中的類型 ;
調(diào)用 testFuture 方法后 , 調(diào)用 then 方法 , 可以獲取 testFuture 方法返回的 String 字符串 , 就是 s 參數(shù) , 打印該字符串 ;
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 方法的第一個(gè)參數(shù) FutureOr<R> onValue(T value) 就是 Future 的 onValue 代表的值 , 類型是 Future 泛型類型 R ;
then 方法的第二個(gè)參數(shù) {Function? onError} 是可選的 , 用于捕獲異常的方法 ;
三、Future 異常捕獲
方式一 : then 方法傳入 onError 參數(shù) ;
在執(zhí)行 返回值是 Future 類型的 testFuture 方法時(shí) , 在 then 方法中 , 第二個(gè)參數(shù) onError
Future<String> testFuture() {return Future.value('success'); }main() {testFuture().then((s) {print(s);}, onError: (e) {print('onError:');print(e);}); }方式二 : 繼續(xù)鏈?zhǔn)秸{(diào)用 , 在 then 方法后 , 繼續(xù)調(diào)用 Future 的 catchError 方法 ;
Future<String> testFuture() {return Future.value('success'); }main() {testFuture().then((s) {print(s);}).catchError((e) {print('catchError:');print(e);}); }注意 : 上述兩個(gè)方法只能二選其一 , 如果都設(shè)置了 , 那么只有 方式一 生效 , 方式二 會(huì)被覆蓋 ;
四、Dart 練習(xí)網(wǎng)站
在 https://dartpad.dartlang.org/ 網(wǎng)站 , 練習(xí) Dart 語(yǔ)言 ;
五、async、await 關(guān)鍵字
async 關(guān)鍵字一般用作 方法的后綴 , 被修飾的方法的 返回值必須是 Future 類型的 ;
方法執(zhí)行時(shí) , 以 同步的形式 執(zhí)行到 await 關(guān)鍵字位置 , 然后 掛起 , 等待后續(xù)異步方法執(zhí)行 ;
異步任務(wù)執(zhí)行完畢后 , await 之后的代碼開(kāi)始執(zhí)行 ;
六、whenComplete 方法
在 Future 執(zhí)行快要結(jié)束時(shí) , 如果想要執(zhí)行一些任務(wù) , 可以在鏈?zhǔn)秸{(diào)用時(shí) , 調(diào)用 Future 的 whenComplete 方法 ;
該方法類似于 try … catch … finally 中的 finally 代碼塊 , 是必定執(zhí)行的代碼 , 即使出險(xiǎn)錯(cuò)誤 , 也會(huì)執(zhí)行該代碼 ;
Future<String> testFuture() {return Future.value('success'); }main() {testFuture().then((s) {print(s);}).catchError((e) {print('catchError:');print(e);}).whenComplete(() {print('whenComplete');}); }七、timeout 方法
有的異步操作可能需要很長(zhǎng)時(shí)間完成 , 這里為異步操作指定一個(gè)超時(shí)時(shí)間 ;
在 Future 鏈?zhǔn)秸{(diào)用時(shí) , 調(diào)用 timeout 方法 , 設(shè)置超時(shí)時(shí)間 ;
void main() {/// 異步操作中會(huì)延遲 3 秒 , 超時(shí)時(shí)間 2 秒 new Future.delayed(new Duration(seconds: 3), () {return 1;}).timeout(new Duration(seconds: 2)).then(print).catchError(print); }八、相關(guān)資源
參考資料 :
- Flutter 官網(wǎng) : https://flutter.dev/
- Flutter 插件下載地址 : https://pub.dev/packages
- Flutter 開(kāi)發(fā)文檔 : https://flutter.cn/docs ( 強(qiáng)烈推薦 )
- 官方 GitHub 地址 : https://github.com/flutter
- Flutter 中文社區(qū) : https://flutter.cn/
- Flutter 實(shí)用教程 : https://flutter.cn/docs/cookbook
- Flutter CodeLab : https://codelabs.flutter-io.cn/
- Dart 中文文檔 : https://dart.cn/
- Dart 開(kāi)發(fā)者官網(wǎng) : https://api.dart.dev/
- Flutter 中文網(wǎng) : https://flutterchina.club/ , http://flutter.axuer.com/docs/
- Flutter 相關(guān)問(wèn)題 : https://flutterchina.club/faq/ ( 入門階段推薦看一遍 )
- GitHub 上的 Flutter 開(kāi)源示例 : https://download.csdn.net/download/han1202012/15989510
- Flutter 實(shí)戰(zhàn)電子書 : https://book.flutterchina.club/chapter1/
重要的專題 :
- Flutter 動(dòng)畫參考文檔 : https://flutterchina.club/animations/
博客源碼下載 :
-
GitHub 地址 : https://github.com/han1202012/flutter_http( 隨博客進(jìn)度一直更新 , 有可能沒(méi)有本博客的源碼 )
-
博客源碼快照 : https://download.csdn.net/download/han1202012/21528472 ( 本篇博客的源碼快照 , 可以找到本博客的源碼 )
總結(jié)
以上是生活随笔為你收集整理的【Flutter】Future 异步编程 ( 简介 | then 方法 | 异常捕获 | async、await 关键字 | whenComplete 方法 | timeout 方法 )的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Flutter】HTTP 网络操作 (
- 下一篇: 【Flutter】FutureBuild