flutter【10】dart語言--非同步支援
非同步支援
dart 中包含很多返回 Future 和 Stream 物件的方法,這些方法都是一步的,比如 I/O。
async 和 await 關鍵字支援非同步程式設計。
處理 Futures
- 使用 async 和 await
- 使用 Future API,參考Future
//使用 async 修飾方法,使用 await 呼叫方法 Future checkVersion() async { var version = await lookUpVersion(); // Do something with version } await lookUpVersion();
要使用 await,其方法必須帶有 async 關鍵字,async 方法只會在遇到第一個 await 表示式時才會執行。
可以使用 try, catch, 和 finally 來處理使用 await 的異常。
try { server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 4044); } catch (e) { // React to inability to bind to the port... }
可以對一個 async 方法多次使用 await 。
var entrypoint = await findEntrypoint(); var exitCode = await runExecutable(entrypoint, args); await flushThenExit(exitCode);
await 表達的返回值通常時 Future ,如果不是,則會自動包裝成一個 Futre。 Future 表示承諾返回一個物件,await 表示式會讓程式暫停,知道該物件可用。
宣告非同步方法
一個 async 方法是函式體被標記為 async 的方法。
//同步方法 String lookUpVersion() => '1.0.0'; //非同步方法 Future<String> lookUpVersion() async => '1.0.0';
非同步方法會返回一個 Future,定義非同步方法時不需要使用 Future API,dart會自動建立 Future 物件。
如果非同步方法沒有返回值,則需要明確標記返回型別為Future<void>
。
處理 Stream
- 使用 async 和 非同步迴圈 await for
- 使用 Stream API,參考Stream
注意:使用 await for 時,要確實需要處理streams的所有結果。例如像UI事件監聽就不需要使用asait for ,因為UI框架會發送無用的streams。
await for (varOrType identifier in expression) { // Executes each time the stream emits a value. }
expression 必須返回 Stream 型別
- 等待,直到 stream 發射一個值
- 使用發射的值,執行迴圈
- 重複1,2,直到stream關閉
停止監聽一個stream,可以使用 break 或者 return 語句。
async for 確保在 async 方法中使用。
main() async { ... await for (var request in requestServer) { handleRequest(request); } ... }