当前位置:网站首页>聊聊 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

边栏推荐
- C development -- WPF simple animation
- ADC采样率(HZ)是什么怎么计算
- 线上面试,该如何更好的表现自己?这样做,提高50%通过率~
- Unity and webgl love each other
- Explain in detail the communication mode between arm A7 and risc-v e907 on Quanzhi v853
- Revit secondary development - shielding warning prompt window
- UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
- Debezium series: binlogreader for source code reading
- 数字化转型:五个步骤推动企业进步
- Interview questions: how to test app performance?
猜你喜欢
DTC社群运营怎么做?
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
新版代挂网站PHP源码+去除授权/支持燃鹅代抽
Redis official ORM framework is more elegant than redistemplate
Yarn cannot view the historical task log of yarn after enabling ACL user authentication. Solution
php 获取图片信息的方法
Why is network i/o blocked?
Digital transformation: five steps to promote enterprise progress
Common verification rules of form components -2 (continuously updating ~)
XMIND mind mapping software sharing
随机推荐
C development - interprocess communication - named pipeline
Yarn开启ACL用户认证之后无法查看Yarn历史任务日志解决办法
ASEMI整流桥KBPC1510的型号数字代表什么
Amesim2016 and matlab2017b joint simulation environment construction
Sword finger offer 27 Image of binary tree
There is another problem just online... Warm
Debezium系列之:引入对 LATERAL 运算符的支持
安踏DTC | 安踏转型,构建不只有FILA的增长飞轮
Form组件常用校验规则-2(持续更新中~)
知识点滴 - PCB制造工艺流程
Line test - graphic reasoning - 4 - alphabetic class
全面掌控!打造智慧城市建设的“领导驾驶舱”
Unity technical notes (I) inspector extension
IP network active evaluation system -- x-vision
Line test - graphic reasoning -5- one stroke class
开发那些事儿:Go加C.free释放内存,编译报错是什么原因?
7-18 simple simulation of banking business queue
Debezium series: binlogreader for source code reading
线上面试,该如何更好的表现自己?这样做,提高50%通过率~
Revit secondary development - get the project file path