当前位置:网站首页>聊聊 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
边栏推荐
- 全面掌控!打造智慧城市建设的“领导驾驶舱”
- Interview questions: how to test app performance?
- Personal statement of testers from Shuangfei large factory: is education important for testers?
- Leetcode interview question 02.07 Linked list intersection [double pointer]
- Force deduction - question 561 - array splitting I - step by step parsing
- Sword finger offer 27 Image of binary tree
- Matplotlib quick start
- Revit secondary development - intercept project error / warning pop-up
- Time convolution Network + soft threshold + attention mechanism to realize residual life prediction of mechanical equipment
- Leetcode94. Middle order traversal of binary trees
猜你喜欢
不夸张地说,这是我见过最通俗易懂的,pytest入门基础教程
肠道里的微生物和皮肤上的一样吗?
Sword finger offer 27 Image of binary tree
Explain in detail the communication mode between arm A7 and risc-v e907 on Quanzhi v853
新版代挂网站PHP源码+去除授权/支持燃鹅代抽
Why is network i/o blocked?
Online interview, how to better express yourself? In this way, the passing rate will be increased by 50%~
Yarn cannot view the historical task log of yarn after enabling ACL user authentication. Solution
Unity FAQ (I) lack of references
Redis cluster installation
随机推荐
PCL .vtk文件与.pcd的相互转换
Aspose. Word operation word document (I)
CTF练习
微服务架构开源框架详情介绍
Leetcode19. Delete the penultimate node of the linked list [double pointer]
Redis cluster installation
How to judge whether the input content is "number"
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
UWA Q & a collection
Visual studio 2019 installation
Micro service remote debug, nocalhost + rainbow micro service development second bullet
Leetcode94. Middle order traversal of binary trees
行测-图形推理-9-线条问题类
开发那些事儿:Go加C.free释放内存,编译报错是什么原因?
数字化转型:五个步骤推动企业进步
Failed to initialize rosdep after installing ROS
Why is network i/o blocked?
7-18 simple simulation of banking business queue
消费品企业敏捷创新转型案例
全面掌控!打造智慧城市建设的“领导驾驶舱”