- if and else
- for loops
- while and do-while loops
- break and continue
- switch and case
- assert
switch
Dart 的switch支持 integer, string, 或 用==比較編譯時(shí)常量. 被比較的實(shí)列的類必須相同 (不能是任何它的子類),并且不能重載 ==運(yùn)算符.也支持 Enum 類型。
每個(gè)非空 case 以break 語句來結(jié)束. 結(jié)束 case 的其他方法還有 continue, throw, 或者 return 語句.
var command = 'OPEN';
switch (command) {
case 'CLOSED':
executeClosed();
break;
case 'PENDING':
executePending();
break;
case 'APPROVED':
executeApproved();
break;
case 'DENIED':
executeDenied();
break;
case 'OPEN':
executeOpen();
break;
default:
executeUnknown();
}
省略號(hào)break會(huì)報(bào)錯(cuò):
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
Dart支持空 case分支:
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
continue :
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;
}
case 分支可以定義局部變量, 只在此分支內(nèi)可見.