做者 | 弗拉德
来源 | 弗拉德(公众号:fulade_me)html
Dart语言的控制语句跟其余常见语言的控制语句是同样的,基本以下:git
文章首发地址 github
Dart 支持 if - else
语句,其中 else
是可选的,好比下面的例子。ide
int i = 0; if (i == 0) { print("value 0"); } else if (i == 1) { print("value 1"); } else { print("other value"); }
若是要遍历的对象实现了 Iterable
接口,则能够使用 forEach()
方法,若是不须要使用到索引,则使用 forEach
方法是一个很是好的选择:url
Iterable
接口实现了不少方法,好比说forEach()、any()、where()
等,这些方法能够大大精简咱们的代码,减小代码量。 code
var callbacks = []; for (var i = 0; i < 2; i++) { callbacks.add(() => print(i)); } callbacks.forEach((c) => c());
像 List
和 Set
等,咱们一样能够使用 for-in
形式的 迭代:htm
var collection = [1, 2, 3]; for (var x in collection) { print(x); // 1 2 3 }
while 循环会在执行循环体前先判断条件:对象
var i = 0; while (i < 10) { i++; print("i = " + i.toString()); }
do-while
循环则会先执行一遍循环体 再 判断条件:索引
var i = 0; do { i++; print("i = " + i.toString()); } while (i < 10);
使用 break
能够中断循环:接口
for (int i = 0; i < 10; i++) { if (i > 5) { print("break now"); break; } print("i = " + i.toString()); }
使用 continue
能够跳过本次循环直接进入下一次循环:
for (int i = 0; i < 10; ++i) { if (i < 5) { continue; } print("i = " + i.toString()); }
因为 List实现了 Iterable 接口,则能够简单地使用下述写法:
``` Dart:
[0,1, 2, 3, 4, 5, 6, 7, 8, 9].where((i) => i > 5).forEach((i) {
print("i = " + i.toString());
});
##### **Switch 和 Case** Switch 语句在 Dart 中使用 `==` 来比较整数、字符串或编译时常量,比较的两个对象必须是同一个类型且不能是子类而且没有重写 `==` 操做符。 枚举类型很是适合在 Switch 语句中使用。 每个 `case` 语句都必须有一个 `break` 语句,也能够经过 `continue、throw` 或者 `return` 来结束 `case` 语句。 当没有 `case` 语句匹配时,能够使用 `default` 子句来匹配这种状况: ``` Dart var command = 'OPEN'; switch (command) { case 'CLOSED': print('CLOSED'); break; case 'PENDING': print('PENDING'); break; case 'APPROVED': print('APPROVED'); break; case 'DENIED': print('DENIED'); break; case 'OPEN': print('OPEN'); break; default: print('UNKNOW'); }
可是,Dart
支持空的 case
语句,以下:
var command = 'CLOSED'; switch (command) { case 'CLOSED': // case 语句为空时的 fall-through 形式。 case 'NOW_CLOSED': // case 条件值为 CLOSED 和 NOW_CLOSED 时均会执行该语句。 print(command); break; }
在开发过程当中,能够在条件表达式为 false
时使用 assert, 来中断代码的执行,提示出错误。你能够在本文中找到大量使用 assert
的例子。下面是相关示例:
// 确保变量值不为 null (Make sure the variable has a non-null value) assert(text != null); // 确保变量值小于 100。 assert(number < 100); // 确保这是一个 https 地址。 assert(urlString.startsWith('https')); assert 的第二个参数能够为其添加一个字符串消息。 assert(urlString.startsWith('https'),'URL ($urlString) should start with "https".');
assert
的第一个参数能够是值为布尔值的任何表达式。若是表达式的值为true
,则断言成功,继续执行。若是表达式的值为false
,则断言失败,抛出一个 AssertionError
异常。
注意:
在生产环境代码中,断言会被忽略,与此同时传入 assert
的参数不被判断。
本文全部代码都已上传到Github