You can control the flow of your Dart code using any of the following:
if and else
for loops
while and do-while loops
break and continue
switch and case
assert
1:if...else...
这个几乎每个编程语言都有if条件判断
void main() {
bool isRaining = true;
if (isRaining) {
print("true---->");
} else {
print("false---->");
}
}
当然了中间也可以使用else if()
for循环
void main() {
for (var i = 0; i < 5; i++) {
print(i);
}
}
While and do-while
void main() {
bool isDone = false;
while (!isDone) {
print("haha");
}
}
do-while
void main() {
int a = 10;
do {
a--;
print(a);
} while (a>=0);
}
break 终止循环
void main() {
test();
}
void test(){
for(int i = 0;i<10;i++){
if(i==5){
break;
}
print(i);
}
}
continue 跳过本次条件还会执行
void main() {
test();
}
void test(){
for(int i = 0;i<10;i++){
if(i==5){
continue;
}
print(i);
}
}
Switch and case
Switch statements in Dart compare integer, string, or compile-time constants using ==
. The compared objects must all be instances of the same class (and not of any of its subtypes), and the class must not override ==
. Enumerated types work well in switch
statements.
翻译:
Dart中的Switch语句使用==比较整数、字符串或编译时常量。被比较的对象必须都是同一个类的实例(而不是它的任何子类型),并且类不能覆盖==。枚举类型在switch语句中工作得很好
void main() {
var command = 'OPEN';
switch (command) {
case 'CLOSED':
print("CLOSED----");
break;
case 'PENDING':
print("PENDING----");
break;
case 'APPROVED':
print("APPROVED----");
break;
case 'DENIED':
print("DENIED----");
break;
case 'OPEN':
print("OPEN----");
break;
default:
print("default----");
}
}
感觉没啥好说的