10.空安全 null safe
·
空安全
-
减少数据异常错误
-
提高程序性能
一、默认不可空
String title = 'ducafecat';
二、type? 可空
String? title = null;
三、value! 值保证不为空,主观上
String? title = 'ducafecat';
String newTitle = title!;
四、value?. 不为空才执行
String? title = 'ducafecat';
bool isEmpty = title?.isEmpty();
五、value?? 如果空执行
String? title = 'ducafecat';
String newTitle = title ?? 'cat';
六、late 使用
延迟加载修饰符(延迟初始化);
声明一个全局不可控变量,申明时不初始化,在后面再初始化。
即使用late后,允许你对全局不可控变量,可以延后初始化。
1.未使用late

2.使用late
late String description;
void main() {
description = 'Feijoada!';
print(description);
}
七、List、泛型
List<String?>? l;
l = [];
l.add(null);
l.add('a');
print(l);
| 类型 | 集合是否可空 | 数据项是否可空 |
|---|---|---|
| List<String> | no | no |
| List<String>? | yes | no |
| List<String?> | no | yes |
| List<String?>? | yes | yes |
八、Map
Map<String, String?>? m;
m = {};
m['a'] = 'b';
m['b'] = null;
print(m);
| 类型 | 集合是否可空 | 数据项是否可空 |
|---|---|---|
| Map<String, int> | no | no* |
| Map<String, int>? | yes | no* |
| Map<String, int?> | no | yes |
| Map<String, int?>? | yes | yes |
更多推荐
所有评论(0)