作者 | 弗拉德
起源 | 弗拉德(公众号:fulade_me)
管制语句
Dart语言的管制语句跟其余常见语言的管制语句是一样的,根本如下:
- if 和 else
- for 循环
- while 和 do-while 循环
- break 和 continue
- switch 和 case
- assert
文章首发地址
If 和 Else
Dart 反对 if - else
语句,其中 else
是可选的,比方上面的例子。
int i = 0;if (i == 0) { print("value 0");} else if (i == 1) { print("value 1");} else { print("other value");}
如果要遍历的对象实现了 Iterable
接口,则能够应用 forEach()
办法,如果不须要应用到索引,则应用 forEach
办法是一个十分好的抉择:
Iterable
接口实现了很多办法,比如说forEach()、any()、where()
等,这些办法能够大大精简咱们的代码,缩小代码量。
var callbacks = [];for (var i = 0; i < 2; i++) { callbacks.add(() => print(i));}callbacks.forEach((c) => c());
像 List
和 Set
等,咱们同样能够应用 for-in
模式的 迭代:
var collection = [1, 2, 3];for (var x in collection) { print(x); // 1 2 3}
While 和 Do-While
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 和 Continue
应用 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 接口,则能够简略地应用下述写法:
[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
子句来匹配这种状况:
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
的参数不被判断。
视频教程
https://www.bilibili.com/vide...
本文所有代码都已上传到Github