if else

  1. if (isRaining()) {
  2. you.bringRainCoat();
  3. } else if (isSnowing()) {
  4. you.wearJacket();
  5. } else {
  6. car.putTopDown();
  7. }

for

标准 for:

  1. var message = StringBuffer('Dart is fun');
  2. for (var i = 0; i < 5; i++) {
  3. message.write('!');
  4. }

这种利用闭包的是安全的, 输出 0, 1:

  1. var callbacks = [];
  2. for (var i = 0; i < 2; i++) {
  3. callbacks.add(() => print(i));
  4. }
  5. callbacks.forEach((c) => c());

Iterable 的 forEach:

  1. candidates.forEach((candidate) => candidate.interview());

Iterable 的 for-in:

  1. var collection = [0, 1, 2];
  2. for (var x in collection) {
  3. print(x); // 0 1 2
  4. }

while

先判断条件:

  1. while (!isDone()) {
  2. doSomething();
  3. }

do-whild

先进行循环体:

  1. do {
  2. printLine();
  3. } while (!atEndOfPage());

break

  1. while (true) {
  2. if (shutDownRequested()) break;
  3. processIncomingRequests();
  4. }

continue

  1. for (int i = 0; i < candidates.length; i++) {
  2. var candidate = candidates[i];
  3. if (candidate.yearsExperience < 5) {
  4. continue;
  5. }
  6. candidate.interview();
  7. }

dart 风格

  1. candidates
  2. .where((c) => c.yearsExperience >= 5)
  3. .forEach((c) => c.interview());

switch-case

  • 比较的类型都是相同类
  • 不能有子类

可以使用:

  • break
  • continue
  • throw
  • return
  1. var command = 'OPEN';
  2. switch (command) {
  3. case 'CLOSED':
  4. executeClosed();
  5. break;
  6. case 'PENDING':
  7. executePending();
  8. break;
  9. case 'APPROVED':
  10. executeApproved();
  11. break;
  12. case 'DENIED':
  13. executeDenied();
  14. break;
  15. case 'OPEN':
  16. executeOpen();
  17. break;
  18. default:
  19. executeUnknown();
  20. }

必须要有 clause:

  1. var command = 'OPEN';
  2. switch (command) {
  3. case 'OPEN':
  4. executeOpen();
  5. // ERROR: Missing break
  6. case 'CLOSED':
  7. executeClosed();
  8. break;
  9. }

fall-through 形式允许省略 clause:

  1. var command = 'CLOSED';
  2. switch (command) {
  3. case 'CLOSED': // Empty case falls through.
  4. case 'NOW_CLOSED':
  5. // Runs for both CLOSED and NOW_CLOSED.
  6. executeNowClosed();
  7. break;
  8. }

continue 形式的 fall-through:

  • 注意下面代码中 nowClosed 的作用域
  1. var command = 'CLOSED';
  2. switch (command) {
  3. case 'CLOSED':
  4. executeClosed();
  5. continue nowClosed;
  6. // Continues executing at the nowClosed label.
  7. nowClosed:
  8. case 'NOW_CLOSED':
  9. // Runs for both CLOSED and NOW_CLOSED.
  10. executeNowClosed();
  11. break;
  12. }

assert

断言失败会抛出 AssertionError 异常.

当是以下情况时, 断言功能启用:

  • Flutter 启用 debug mode
  • dartdev 开发工具
  • dar, dart2js 工具使用 --enable-asserts 命令标记
  1. // Make sure the variable has a non-null value.
  2. assert(text != null);
  3. // Make sure the value is less than 100.
  4. assert(number < 100);
  5. // Make sure this is an https URL.
  6. assert(urlString.startsWith('https'));

附加字符串:

  1. assert(urlString.startsWith('https'),
  2. 'URL ($urlString) should start with "https".');