flutter【5】dart語言--流程控制語句
if-else
條件必須是布林型的值。
if (isRaining()) { you.bringRainCoat(); } else if (isSnowing()) { you.wearJacket(); } else { car.putTopDown(); }
for迴圈
var message = StringBuffer('Dart is fun'); for (var i = 0; i < 5; i++) { message.write('!'); }
dart for迴圈中的閉包可以捕獲迴圈的 index 索引值, 來避免 JavaScript 中常見的問題。
var callbacks = []; for (var i = 0; i < 2; i++) { callbacks.add(() => print(i)); } callbacks.forEach((c) => c());
輸出的結果為所期望的 0 和 1。但是 上面同樣的程式碼在 JavaScript 中會列印兩個 2。
for 迴圈遍歷
//物件實現了 Iterable 介面 candidates.forEach((candidate) => candidate.interview()); //for in 遍歷 var collection = [0, 1, 2]; for (var x in collection) { print(x); }
while 和 do-while
while 迴圈在執行迴圈之前先判斷條件是否滿足:
while (!isDone()) { doSomething(); }
而 do-while 迴圈是先執行迴圈程式碼再判斷條件:
do { printLine(); } while (!atEndOfPage());
break 和 continue
使用 break 來終止迴圈:
while (true) { if (shutDownRequested()) break; processIncomingRequests(); }
使用 continue 來開始下一次迴圈:
for (int i = 0; i < candidates.length; i++) { var candidate = candidates[i]; if (candidate.yearsExperience < 5) { continue; } candidate.interview(); }
上面的程式碼在實現 Iterable 介面物件上可以使用下面的寫法:
candidates.where((c) => c.yearsExperience >= 5) .forEach((c) => c.interview());
Switch and case
- Dart 中的 Switch 語句使用 == 比較 integer、string、或者編譯時常量。
- 比較的物件必須都是同一個類的例項(並且不是其子類),class 不能覆寫 == 操作符。
- Enumerated types 非常適合 在 switch 語句中使用。
- 每個非空的 case 語句都必須有一個 break 語句。
- 空 case 語句中可以不要 break 語句。
- 可以通過 continue、 throw 或 者 return 來結束非空 case 語句。
- 如果需要實現繼續到下一個 case 語句中繼續執行,則可以使用 continue 語句跳轉到對應的標籤(label)處繼續執行:
- 當沒有 case 語句匹配的時候,可以使用 default 語句來匹配這種預設情況。
- 每個 case 語句可以有區域性變數,區域性變數 只有在這個語句內可見。
var command = 'CLOSED'; switch (command) { case 'CLOSED': executeClosed(); continue nowClosed; // Continues executing at the nowClosed label. nowClosed: case 'NOW_CLOSED': // Runs for both CLOSED and NOW_CLOSED. executeNowClosed(); break; }
Assert(斷言)
- 如果條件表示式結果不滿足需要,則可以使用 assert 語句倆打斷程式碼的執行
- 斷言只在檢查模式下執行有效,如果在生產模式 執行,則斷言不會執行。
- 斷言執行失敗,會丟擲一個異常 AssertionError
// Make sure the variable has a non-null value. assert(text != null); // Make sure the value is less than 100. assert(number < 100); // Make sure this is an https URL. assert(urlString.startsWith('https')); //為 Assert 繫結一個訊息 assert(urlString.startsWith('https'), 'URL ($urlString) should start with "https".');