可以使用下面的语句来控制 Dart 代码的流程:
if and else for loops while and do-while loops break and continue switch and case assert使用 try-catch 和 throw 还能影响控制流程的 跳转,详情请参考Exceptions。
If android else
Dart 支持 if 语句以及可选的 else ,例如下面的示例。 另参考 条件表达式。
if (isRaining()) { you.bringRainCoat(); } else if (isSnowing()) { you.wearJacket(); } else { car.putTopDown(); }
注意, Dart 中和 JavaScript 对待 true 的区别。 参考 布尔值 获取更多信息。
For loops
可以使用标准的 for 循环:
var message = new 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。
如果要遍历的对象实现了 Iterable 接口,则可以使用 forEach() 方法。如果没必要当前遍历的索引,则使用 forEach() 方法 是个非常好的选择:
candidates.forEach((candidate) => candidate.interview());
List 和 Set 等实现了 Iterable 接口的类还支持 for-in 形式的 遍历:
var collection = [0, 1, 2]; for (var x in collection) { print(x); }
While and do-while
while 循环在执行循环之前先判断条件是否满足:
while (!isDone()) { doSomething(); }
而 do-while 循环是先执行循环代码再判断条件:
do { printLine(); } while (!atEndOfPage());
Break and 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 语句中使用。
注意: Dart 中的 Switch 语句仅适用于有限的情况, 例如在 解释器或者扫描器中使用。
每个非空的 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(); }
下面的示例代码在 case 中省略了 break 语句, 编译的时候将会出现一个错误:
var command = 'OPEN'; switch (command) { case 'OPEN': executeOpen(); // ERROR: Missing break causes an exception!! case 'CLOSED': executeClosed(); break; }
但是,在 Dart 中的空 case 语句中可以不要 break 语句:
var command = 'CLOSED'; switch (command) { case 'CLOSED': // Empty case falls through. case 'NOW_CLOSED': // Runs for both CLOSED and NOW_CLOSED. executeNowClosed(); break; }
如果你需要实现这种继续到下一个 case 语句中继续执行,则可以 使用 continue 语句跳转到对应的标签(label)处继续执行:
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 语句俩打断代码的执行。 下面介绍如何使用断言。 下面是一些示例代码:
// 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 方法的参数可以为任何返回布尔值的表达式或者方法。 如果返回的值为 true, 断言执行通过,执行结束。 如果返回值为 false, 断言执行失败,会抛出一个异常 AssertionError)。