if else
if (isRaining()) {
you.bringRainCoat();
} else if (isSnowing()) {
you.wearJacket();
} else {
car.putTopDown();
}
for
标准 for:
var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
message.write('!');
}
这种利用闭包的是安全的, 输出 0, 1:
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
Iterable 的 forEach:
candidates.forEach((candidate) => candidate.interview());
Iterable 的 for-in:
var collection = [0, 1, 2];
for (var x in collection) {
print(x); // 0 1 2
}
while
先判断条件:
while (!isDone()) {
doSomething();
}
do-whild
先进行循环体:
do {
printLine();
} while (!atEndOfPage());
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();
}
dart 风格
candidates
.where((c) => c.yearsExperience >= 5)
.forEach((c) => c.interview());
switch-case
- 比较的类型都是相同类
- 不能有子类
可以使用:
- break
- continue
- throw
- return
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();
}
必须要有 clause:
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
fall-through 形式允许省略 clause:
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
continue 形式的 fall-through:
- 注意下面代码中 nowClosed 的作用域
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;
}
assert
断言失败会抛出 AssertionError 异常.
当是以下情况时, 断言功能启用:
- Flutter 启用 debug mode
- dartdev 开发工具
- dar, dart2js 工具使用
--enable-asserts
命令标记
// 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".');