# 空安全 null safe
- 减少数据异常错误
- 提高程序性能
# null
# 默认不可空
String title = 'Blog';
1
# type? 可空
String? title = null;
1
# value! 值保证不为空
String? title = 'Blog';
String newTitle = title!;
1
2
2
value为空的话, 编译时不报错, 运行时报错
# value?. 不为空才执行
String? title = 'Blog';
bool isEmpty = title?.isEmpty();
1
2
2
# value?? 为空才执行
String? title = 'Blog';
bool isEmpty = title?? "Articles";
1
2
2
# late
late
延迟加载修饰符
// 声明一个不可空的变量,并在声明后初始化
late String description;
// 加上 late 后就可以不用构造函数的时候初始化了
class lateTest {
late final test;
lateTest();
}
void main(List<String> args) {
description = 'Feijoada!';
var lt = new lateTest();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 泛型
# List
类型 | 集合是否可空 | 数据项是否可空 |
---|---|---|
List | no | no |
List | yes | no |
List<String?> | no | yes |
List<String?>? | yes | yes |
# Map
类型 | 集合是否可空 | 数据项是否可空 |
---|---|---|
Map<String, int> | no | no* |
Map<String, int>? | yes | no* |
Map<String, int?> | no | yes |
Map<String, int?>? | yes | yes |
*
可能返回空