Flutter: Future delay, async + await
第一種: future 當delay用"
code 1:
Future<String> future = Future.delayed(
Duration(seconds: 5),
() => "Latest News",
);
future.then((news) {
print(news);
});
result:
(after 5 sec)
Latest News
-----
Future<void> asyncAwait() async{
print('Started');
try{
await Future.delayed(Duration(seconds: 5));
print('Completed first');
await Future.delayed(Duration(seconds: 1));
print('Completed second');
}catch(e){
print('failed: ${e.toString()}');
}
}
asyncAwait();
Result:
Started
(after 5 sec)
Completed first
(after 1 sec)
Completed second
-----
簡單講, dart 的 future 就有點像是android中的handler post delay.
void _do_something1() {
/// 買披薩
Future<void> getPizza() {
return Future.delayed(Duration(seconds: 5), () => print('Bacon Pizza'));
}
getPizza();
print('Baking~');
}
向上圖程式碼: output
Baking~
(after 5 sec...)
Bacon Pizza
-------
第二種: future當異步函數使用: 配合使用async + await (Blocking i/o or asynchronous functions)
/// 買蛋塔
Future<String> getEggTower() async {
final quantity = await getQuantity();
return 'Buy $quantity eggTower';
}
/// 取得數量
Future<int> getQuantity() async =>
Future.delayed(Duration(seconds: 3), () => 2);
因為網路上存取資料你也不知道要等待多久,當然不可能用delay幾秒的方式處理.
這種異步處理函式就很重要.
凡是有用到異步處理的function都要加上async 關鍵字.
在需要等待的function call前加上await關鍵字.
他就會等待函式執行完,而不須指定等待秒數(千萬步要指定秒數delay,這是最笨的方法).
順序處理
你可以使用多個 await
表達式來確保各個語句在執行下一個語句之前完成:
// Sequential processing using async and await. // 使用關鍵字 async 和 await 順序處理異步函數邏輯 main() async { await expensiveA(); await expensiveB(); doSomethingWith(await expensiveC()); }
函數 expensiveB()
將會在函數 expensiveA()
執行完畢後才執行,接下來的其它類似函數也如此。
留言
張貼留言