当前位置:网站首页>聊聊 Dart 的空安全 (null safety) 特性
聊聊 Dart 的空安全 (null safety) 特性
2022-07-07 21:49:00 【InfoQ】
前言
null safety
null safety
null safety
Nullable 和 non-nullable 类型
null satety
String
String
null
?
String?
null
String? str1;
String str2;
// OK
str1 = null;
// 报错
str2 = null;
// OK
List<String?> strList1 = ['a', null, 'c'];
// 报错
List<String> strList2 = ['a', null, 'c'];
空断言操作符!
valiable!.xx
nullable
null
!
int? couldReturnNullButDoesnt() => -3;
void main() {
int? nullableInt = 1;
List<int?> intListHasNull = [2, null, 4];
int a = nullableInt!;
int b = intListHasNull.first!;
int c = couldReturnNullButDoesnt()!.abs();
print('a is $a.');
print('b is $b.');
print('c is $c.');
}
类型提升(Type promotion)
String? str;
if (str != null) {
print(str); //已经确保不为空,不会编译出错
}
late 关键字
late
late
- 目前还没有给该变量赋值;
- 我们将在之后才给该变量赋值;
- 我们保证在使用该变量前肯定会对其赋值。
class Meal {
late String _decription; //错误声明
set description(String desc) {
_description = 'Meal Description: $desc';
}
String get description => _description;
}
void main() {
final myMeal = Meal();
myMeal.description = 'Feijoada';
print(myMeal.description);
}
late
late
if
class Team {
late final Coach coach;
}
class Coach {
late final Team team;
}
void main() {
final myTeam = Team();
final myCoach = Coach();
myTeam.coach = myCoach;
myCoach.team = myTeam;
print('搞定!');
}
升级修改
- 类属性:非空类属性默认需要由初始值,如果类属性会在别的方法中初始化,那可以加上
late
关键字,表示该属性稍后会被初始化,而且是非空的。如果属性可能为空,那么就加上?
空标识。这种可为空的属性使用的时候需要特别注意,需要检查是否为空才可以使用,或者使用variable?.xx
这种形式访问,如果明确属性有值,则需要使用!强制指定为非空,如variable!.xx
。
- 方法参数:根据需要设置参数是否是可为空或必传参数,必传的参数加上在参数声明前加上
required
关键字,可为空的加上?
标识。
- 返回值:如果返回值可能为
null
,就在返回参数后加上?
标识。如果是集合对象中的某个对象为空,那么需要在集合的类型后加上?标识,例如List<int?>
。
- 将依赖最低的 Dart 版本修改为2.12.0
environment:
sdk: ">=2.12.0 <3.0.0"
- 修改部分第三方插件依赖,升级到支持null safety 版本,具体可以参考 pub 上的版本说明。
Dio 踩坑
Dio
DioError [DioErrorType.other]: type 'Null' is not a subtype of type 'Object'
issue
Dio
CookieManager
headers
Cookie
_cookie
null
_cookie
Cookie
// CookieManager 之前的代码,_cookie 可能为 null 导致 Dio 报异常
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
options.headers['Cookie'] = _cookie;
return super.onRequest(options, handler);
}
// 修改后
@override
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
// null safety后需要不为空才可以设置
if (_cookie != null) {
options.headers['Cookie'] = _cookie;
}
return super.onRequest(options, handler);
}
总结
null safety
null safety
Dart
dynamic
RequestOptions options
headers
Map<String, dynamic>
null
dynamic
null

边栏推荐
- 全面掌控!打造智慧城市建设的“领导驾驶舱”
- The PHP source code of the new website + remove authorization / support burning goose instead of pumping
- Why is network i/o blocked?
- How to choose the appropriate automated testing tools?
- UWA Q & a collection
- Sword finger offer 27 Image of binary tree
- ASEMI整流桥KBPC1510的型号数字代表什么
- Cause analysis and solution of too laggy page of [test interview questions]
- Quick sort (diagram +c code)
- 软件测评中心▏自动化测试有哪些基本流程和注意事项?
猜你喜欢
行测-图形推理-6-相似图形类
Line test graph reasoning graph group class
Early childhood education industry of "screwing bar": trillion market, difficult to be a giant
Select sort (illustration +c code)
Yarn开启ACL用户认证之后无法查看Yarn历史任务日志解决办法
Robot autonomous exploration series papers environment code
Line test - graphic reasoning -5- one stroke class
行測-圖形推理-4-字母類
Unity与WebGL的相爱相杀
知识点滴 - PCB制造工艺流程
随机推荐
Line test - graphic reasoning - 3 - symmetric graphic class
Debezium series: binlogreader for source code reading
Online interview, how to better express yourself? In this way, the passing rate will be increased by 50%~
Early childhood education industry of "screwing bar": trillion market, difficult to be a giant
Transparent i/o model from beginning to end
Sword finger offer 28 Symmetric binary tree
Aspose. Word operation word document (II)
Revit secondary development - cut view
面试百问:如何测试App性能?
Cause analysis and solution of too laggy page of [test interview questions]
Microbial Health Network, How to restore Microbial Communities
0-5VAC转4-20mA交流电流隔离变送器/转换模块
Revit secondary development - get the project file path
The PHP source code of the new website + remove authorization / support burning goose instead of pumping
Unity development --- the mouse controls the camera to move, rotate and zoom
Debezium系列之:支持 mysql8 的 set role 语句
Why is network i/o blocked?
Microservice Remote debug, nocalhost + rainbond microservice Development second Bomb
Details of the open source framework of microservice architecture
php 获取图片信息的方法