前言
你可以使用以下任意一个了控制Dart的代码流程
if和elsefor循环while和do-while循环break和continueswitch和caseassert
你也可以用 try-catch 和throw来影响控制流。
if 和 else
Dart支持可选else语句的if语句,例如:
if (isRaining()) {
you.bringRainCoat();
} else if (isSnowing()) {
you.wearJacket();
} else {
car.putTopDown();
}
不像JavaScript, 条件必须用boolean值。
for 循环
你可以迭代标准的for循环, 例如:
var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
message.write('!');
}
Dart的for循环内部的闭包捕获了索引的值,避免了JavaScript中常见的陷阱。 例如,考虑一下:
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
正如预期的那样,输出为0然后为1。 相比之下,该示例将在JavaScript中打印2然后打印2。
如果要迭代的对象是Iterable,则可以使用forEach()方法。 如果你不需要知道当前的迭代计数器,使用forEach()是一个不错的选择:
candidates.forEach((candidate) => candidate.interview());
可迭代的类例如 List 和 Set 也支持 for-in 形式的迭代
var collection = [0, 1, 2];
for (var x in collection) {
print(x); // 0 1 2
}
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(如list或set),则可以以不同的方式编写该示例:
candidates
.where((c) => c.yearsExperience >= 5)
.forEach((c) => c.interview());
switch 和 case
Dart中的switch语句使用==比较整数,字符串或编译时常量。 比较的两个对象必须都是同一个类的实例(而且不能是其任何子类型),并且该类不能覆写==。 枚举类型在switch语句中也适用。
每个非空case子句以break语句作为结束规则。 结束非空case子句的其他有效方法有continue,throw或return语句。
当没有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();
}
以下示例省略了case子句中的break语句,从而发生错误:
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
但是,Dart确实支持空子句,只允许一种形式的落空(不写子句):
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子句可以具有局部变量,这些变量仅在该子句的范围内可见。
assert
在开发期间,使用assert语句- assert(condition,optionalMessage) - 来正常中断执行,如果布尔条件为false。 你可以在本系列中找到断言语句的示例。 这里还有一些:
// 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(urlString.startsWith('https'),
'URL ($urlString) should start with "https".');
断言的第一个参数可以是解析为布尔值的任何表达式。 如果表达式的值为true,则断言成功并继续执行。 如果为false,则断言失败并抛出异常(AssertionError)。
断言何时起作用? 这取决于你使用的工具和框架:
- Flutter 可以在 debug 模式中断言
- 仅限开发的工具(如dartdevc)通常默认启用断言。
- 某些工具(如dart和dart2js)通过命令行标志支持断言:
--enable-asserts。
在生产环境的代码中,将忽略断言,并且不会计算断言的参数。