Dart 语言入门 (五)
Dart 语言系列
Control flow statements (控制流语句)
你可以控制你Dart 代码的流程使用下面任何一个:
-
ifandelse -
forloops -
whileanddo-whileloops -
breakandcontinue -
switchandcase assert
你可以影响控制流使用 try-catch 和 throw。
If and else
Dart 支持 if 语句和可选的else语句,正如下面例子展示的,也可以参考 conditional expressions
if (isRaining()) {
you.bringRainCoat();
} else if (isSnowing()) {
you.wearJacket();
} else {
car.putTopDown();
}
不同于JavaScript,条件必须使用 boolean 值,其他的不行。更多信息参考 Booleans
For loops
你可以使用标准的 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));
}
callback.forEcha((c) => c());
如同预期,先输出 0,然后是 1.相反的是, 在 JavaScript这个例子将会一直输出 2。
如果你要迭代的对象是可迭代的,你可以使用 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 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](https://api.dartlang.org/stable/dart-core/Iterable-class.html) 例如list 或者set:
candidates
.where((c) => c.yearsExperience >= 5)
.forEach((c) => c.interview());
Switch and case
Switch 语句在Dart中比较 interger string 或者 编译期常量使用 ==.比较的对象必须是相同类(不能是其子类),并且类不能覆盖==,
Enumerated types 在 switch 中运行的很好.
Note: 在 Dart 中switch语句用于特定的环境中, 例如在interpreters 或者 scanners
每一个非空的 case 条件 以 break 语句结束,作为规范。其他有效的方法以一个非空 case条件是 continue throw 或者 return 语句.
使用default 条件 来执行代码当没有 case条件匹配:
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();
}
下面的例子省略了 break 语句在 case条件中,于是产生了错误:
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 条件可以有局部变量,只有在条件范围内是可见的.
Assert
使用 assert 语句来终止 正常的执行如果boolean 条件是 false.你可以发现关于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'));
Note:Assert 语句在生产代码中没有作用; 仅仅在开发环境有效. Flutter 在 debug mode 中可以使用 assert. 开发工具例如 dartdevc 通常默认支持 assert。一些工具, 例如: dart和dart2js 支持asserts 通过命令行标志: --enable-asserts
为了给 assert 添加一个消息,可以在第二个参数添加一个文字:
assert(urlString.startsWith('https'),
'URL ($urlString) should start with "https".');
assert 第一个参数 可以是任何解析为布尔值的条件。 如果条件值是真的,则断言成功并且继续执行. 如果是假的,则断言失败并且会抛出异常。