【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 練習網站
在 https://dartpad.dartlang.org/ 網站 , 練習 Dart 語言 ;
五、async、await 關鍵字
async 關鍵字一般用作 方法的后綴 , 被修飾的方法的 返回值必須是 Future 類型的 ;
方法執行時 , 以 同步的形式 執行到 await 關鍵字位置 , 然后 掛起 , 等待后續異步方法執行 ;
異步任務執行完畢后 , await 之后的代碼開始執行 ;
六、whenComplete 方法
在 Future 執行快要結束時 , 如果想要執行一些任務 , 可以在鏈式調用時 , 調用 Future 的 whenComplete 方法 ;
該方法類似于 try … catch … finally 中的 finally 代碼塊 , 是必定執行的代碼 , 即使出險錯誤 , 也會執行該代碼 ;
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 方法 , 設置超時時間 ;
void main() {/// 異步操作中會延遲 3 秒 , 超時時間 2 秒 new Future.delayed(new Duration(seconds: 3), () {return 1;}).timeout(new Duration(seconds: 2)).then(print).catchError(print); }八、相關資源
參考資料 :
- Flutter 官網 : https://flutter.dev/
- Flutter 插件下載地址 : https://pub.dev/packages
- Flutter 開發文檔 : https://flutter.cn/docs ( 強烈推薦 )
- 官方 GitHub 地址 : https://github.com/flutter
- Flutter 中文社區 : https://flutter.cn/
- Flutter 實用教程 : https://flutter.cn/docs/cookbook
- Flutter CodeLab : https://codelabs.flutter-io.cn/
- Dart 中文文檔 : https://dart.cn/
- Dart 開發者官網 : https://api.dart.dev/
- Flutter 中文網 : https://flutterchina.club/ , http://flutter.axuer.com/docs/
- Flutter 相關問題 : https://flutterchina.club/faq/ ( 入門階段推薦看一遍 )
- GitHub 上的 Flutter 開源示例 : https://download.csdn.net/download/han1202012/15989510
- Flutter 實戰電子書 : https://book.flutterchina.club/chapter1/
重要的專題 :
- Flutter 動畫參考文檔 : https://flutterchina.club/animations/
博客源碼下載 :
-
GitHub 地址 : https://github.com/han1202012/flutter_http( 隨博客進度一直更新 , 有可能沒有本博客的源碼 )
-
博客源碼快照 : https://download.csdn.net/download/han1202012/21528472 ( 本篇博客的源碼快照 , 可以找到本博客的源碼 )
總結
以上是生活随笔為你收集整理的【Flutter】Future 异步编程 ( 简介 | then 方法 | 异常捕获 | async、await 关键字 | whenComplete 方法 | timeout 方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Flutter】HTTP 网络操作 (
- 下一篇: 【Flutter】FutureBuild