0%

dart学习之路(二)

dart 语言学习之路:操作符和流程控制语句

操作符

列举一些 dart 语言中特有的一些操作符

取整 ~/

1
2
3
int a = 3;
int b = 2;
print(a ~/ b); // 1

级联 ..

对一个单一的对象进行一系列的操作的时候使用:

1
2
3
4
querySelector('#confirm') // 获取一个对象
..text = 'Confirm' // 使用它的成员
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));

级联也可以嵌套使用

条件成员访问符 ?.

. 类似,但是运算符左边的对象不能为 null,否则返回 null,若对象不为 null,则返回对象本身:

1
2
3
4
5
List list1; // list1默认值为null
print(list1?.length); // null

List list2 = [];
print(list2?.length); // 0

条件表达式 ??

1
var b = a ?? '123'; // 若 a 为非空则返回 a,否则返回 123

赋值 ??=

仅在变量为 null 时赋值:

1
b ??= value; // 如果b为空,则将值分配给b;否则,b保持不变

循环

迭代的对象是容器(ListSetMap),那么可以使用 forEach 或者 for-in

1
2
3
4
5
6
var collection = [0, 1, 2];

collection.forEach((x) => print(x)); // 0 1 2
for(var x in collection) {
print(x); // 0 1 2
}

if 语句

If 语句的判断条件为 bool 值,与其他语言一样,但有一点区别:
在开发模式非 bool 值会抛出异常,而生产环境会被编译成 false

1
2
3
4
5
if (1) {
print('JavaScript is ok.');
} else {
print('Dart in production mode is ok.');
}

Switch And Case

若想执行完一个 case 还想继续执行其他的 case,可以使用 continue 和标签实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
String state = 'close';
switch (state) {
case 'close':
print('closed');
continue afterClose;
case 'open':
print('open');
break;
afterClose: // 将会执行 close 和 afterClose 这两个分句
case 'afterClose':
print('afterClose');
break;
}