Flutter开发 3.Dart语言基础-流程控制
1. If 和 Else
If 和 Else语句与大多数语言都一样,使用比较简单。
bool isTrue1 = false, isTrue2 = true;
void main() {
if (isTrue1 == true) {
showElement("isTrue1=true");
} else if (isTrue2) {
showElement("isTrue2=true");
} else {
showElement("isTrue1=false and isTrue2=false");
}
}
void showElement(String element) {
isTrue2 = false;
print(element);
}
运行后输出结果
isTrue2=true
2. For 循环
2.1 标准的 for 循环
var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
message.write('!');
}
print(message);
使用官方的例子,向一个StringBuffer对象末尾重复写入五个字符.
运行后输出结果
Dart is fun!!!!!
2.2 for 循环中的闭包
循环中的闭包会自动捕获循环的索引值
var callbacks = [];
for (var i = 1; i <= 3; i++) {
callbacks.add(() => print("i'm callbacks $i"));
}
callbacks.forEach((c) => c());
创建一个函数数组,循环将函数加入到数组中,然后在数组中还引用了循环变量。
运行后输出结果
i'm callbacks 1
i'm callbacks 2
i'm callbacks 3
2.3 for-in 方法
如果要遍历的对象是一个可迭代对象(例如 List 或 Set),并且你不需要知道当前的遍历索引,则可以使用 for-in 方法
var s2 = {"ab", "ac", "ad"};
for (var item in s2) {
print(item);
}
运行后输出结果
ab
ac
ad
2.4 forEach
print方法直接做为参数
var s2 = {"ab", "ac", "ad"};
s2.forEach(print);
运行后输出结果
ab
ac
ad
2.5 While
while 循环会在执行循环体前先判断条件:
var s2 = ["ab", "ac", "ad"];
int count = 0;
int len = s2.length;
while (count < len) {
print("$count-${s2[count]}");
count++;
}
运行后输出结果
0-ab
1-ac
2-ad
2.6 do-while
do-while 循环则会 先执行一遍循环体 再判断条件:
var s2 = ["ab", "ac", "ad"];
int count = 0;
int len = s2.length;
do {
print("$count-${s2[count]}");
count++;
} while (count < len);
运行后输出结果
0-ab
1-ac
2-ad
2.7 Continue
使用 continue 可以跳过本次循环直接进入下一次循环:
int count = 0;
int len = 5;
do {
if (count == 1) {
count++;
continue;
}
print("$count-while end");
count++;
} while (count < len);
运行后输出结果
0-while end
2-while end
3-while end
4-while end
2.8 Break
使用 break 可以中断循环:
int count = 0;
int len = 5;
do {
if (count == 1) {
count++;
break;
}
print("$count-while end");
count++;
} while (count < len);
运行后输出结果
0-while end
2.9 Iterable where
var tmp = [1, 2, 3, 5, 6, 7, 9, 10];
tmp.where((element) => element < 4).forEach((element) {
print(element);
});
运行后输出结果
1
2
3
3. Switch 和 Case
参照官的例子,每一个非空的 case 子句都必须有一个 break 语句,也可以通过 continue、throw 或者 return 来结束非空 case 语句。
不匹配任何 case 语句的情况下,会执行 default 子句中的代码:
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();
}