5.Control flow statements-流程控制(Dart中文文档)

你可以使用如下流程控制符:

  • if and else
  • for loops
  • while and do-while loops
  • break and continue
  • switch and case
  • assert
    同时,你可以用try-catch 和throw去跳出流程控制逻辑,并在异常代码块中进行处理。

If and else

下面是if和else配合使用的示例:

if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}

有点要注意,Dart语言不像JavaScript,if判断必须是Boolean类型对象,不能将null看作false

For loops

for循环示例:

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

在for循环中局部变量再闭包函数中使用,变量值将会是当时的快照值,后续i变动,也不会改变。这个和JavaScript不同。

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

上面的代码,将先输出0,再输出1。而在JavaScript中,都是输出2,这就是两个之间的一个差异

对一个数组对象循环时,如果你不需要知道循环的计数器,可以用forEach写法。

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

数组或者集合也可以用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();
}

如果你是对数组或者集合操作,可以用如下写法:

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

Switch and case

switch可以用数值,字符串,编译常量作为判断值,case后面的对象必须在类中初始化,不能在父类中,通过该对象的类不能重载==。另外,枚举类型也可以作为判断条件。

非空的case,必须使用break,coutinue,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();
}

Dart的非空case必须break,除非你采用coutinue进行跳转。

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break

  case 'CLOSED':
    executeClosed();
    break;
}

Dart支持空的case,处理逻辑和其后续case相同。

var command = 'CLOSED';
switch (command) {
  case 'CLOSED': // Empty case falls through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

如果在非空的case中,你希望switch继续向下判断,可以用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用来在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在生产模式将被忽略。Flutter可以通过debug模式启用assert,IDE上面,只有dartdevc默认支持dart,其它工具,比如dart,dart2js,需要用--enable-asserts来开启assert

assert的带2个参数写法:

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

第六篇准备翻译 Exceptions 异常

posted @ 2018-12-27 09:20  lowezheng  阅读(370)  评论(0编辑  收藏  举报