Dart基础之控制流语句

前言

你可使用如下任意一个了控制Dart的代码流程闭包

  • ifelse
  • for循环
  • whiledo-while循环
  • breakcontinue
  • switchcase
  • assert

你也能够用 try-catchthrow来影响控制流。框架

if 和 else

Dart支持可选else语句的if语句,例如:less

if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}
复制代码

不像JavaScript, 条件必须用boolean值。工具

for 循环

你能够迭代标准的for循环, 例如:ui

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

Dart的for循环内部的闭包捕获了索引的值,避免了JavaScript中常见的陷阱。 例如,考虑一下:this

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

正如预期的那样,输出为0而后为1。 相比之下,该示例将在JavaScript中打印2而后打印2。url

若是要迭代的对象是Iterable,则可使用forEach()方法。 若是你不须要知道当前的迭代计数器,使用forEach()是一个不错的选择:spa

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 和 do-while

while循环在 循环前 计算条件:debug

while (!isDone()) {
  doSomething();
}
复制代码

do-while循环在 循环后 计算条件:

do {
  printLine();
} while (!atEndOfPage());
复制代码

break 和 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(如list或set),则能够以不一样的方式编写该示例:

candidates
    .where((c) => c.yearsExperience >= 5)
    .forEach((c) => c.interview());
复制代码

switch 和 case

Dart中的switch语句使用==比较整数,字符串或编译时常量。 比较的两个对象必须都是同一个类的实例(并且不能是其任何子类型),而且该类不能覆写==。 枚举类型在switch语句中也适用。

每一个非空case子句以break语句做为结束规则。 结束非空case子句的其余有效方法有continuethrowreturn语句。

当没有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

  case 'CLOSED':
    executeClosed();
    break;
}
复制代码

可是,Dart确实支持空子句,只容许一种形式的落空(不写子句):

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语句- assert(condition,optionalMessage) - 来正常中断执行,若是布尔条件为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(urlString.startsWith('https'),
    'URL ($urlString) should start with "https".');
复制代码

断言的第一个参数能够是解析为布尔值的任何表达式。 若是表达式的值为true,则断言成功并继续执行。 若是为false,则断言失败并抛出异常(AssertionError)。

断言什么时候起做用? 这取决于你使用的工具和框架:

  • Flutter 能够在 debug 模式中断言
  • 仅限开发的工具(如dartdevc)一般默认启用断言。
  • 某些工具(如dart和dart2js)经过命令行标志支持断言:--enable-asserts

在生产环境的代码中,将忽略断言,而且不会计算断言的参数。

相关文章
相关标签/搜索