当前位置:网站首页>聊聊 Dart 的空安全 (null safety) 特性
聊聊 Dart 的空安全 (null safety) 特性
2022-07-07 21:49:00 【InfoQ】
前言
null safetynull safetynull safetyNullable 和 non-nullable 类型
null satetyStringStringnull?String?nullString? str1;
String str2;
// OK
str1 = null;
// 报错
str2 = null;
// OK
List<String?> strList1 = ['a', null, 'c'];
// 报错
List<String> strList2 = ['a', null, 'c'];
空断言操作符!
valiable!.xxnullablenull!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 关键字
latelate- 目前还没有给该变量赋值;
- 我们将在之后才给该变量赋值;
- 我们保证在使用该变量前肯定会对其赋值。
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);
}
latelateifclass 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 踩坑
DioDioError [DioErrorType.other]: type 'Null' is not a subtype of type 'Object'issueDioCookieManagerheadersCookie_cookienull_cookieCookie// 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 safetynull safetyDartdynamicRequestOptions optionsheadersMap<String, dynamic>nulldynamicnull
边栏推荐
- Revit secondary development - shielding warning prompt window
- Unity development --- the mouse controls the camera to move, rotate and zoom
- Quick sort (diagram +c code)
- Form组件常用校验规则-2(持续更新中~)
- Apple further entered the financial sector through the 'virtual card' security function in IOS 16
- Leetcode19. Delete the penultimate node of the linked list [double pointer]
- 微生物健康網,如何恢複微生物群落
- PHP method of obtaining image information
- Aspose. Words merge cells
- UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
猜你喜欢

Basic knowledge of binary tree

Basic knowledge of linked list

「开源摘星计划」Loki实现Harbor日志的高效管理

Yarn cannot view the historical task log of yarn after enabling ACL user authentication. Solution

Interview questions: how to test app performance?

Microbial health network, how to restore microbial communities

Unity FAQ (I) lack of references

Select sort (illustration +c code)

PCL .vtk文件与.pcd的相互转换

开发那些事儿:Go加C.free释放内存,编译报错是什么原因?
随机推荐
LeetCode203. Remove linked list elements
Class implementation of linear stack and linear queue (another binary tree pointer version)
Explain in detail the communication mode between arm A7 and risc-v e907 on Quanzhi v853
Unity FAQ (I) lack of references
Debezium系列之:源码阅读之SnapshotReader
行测-图形推理-1-汉字类
Cause analysis and solution of too laggy page of [test interview questions]
7-51 combination of two ordered linked list sequences
ASP. Net core introduction V
Signal feature extraction +lstm to realize gear reducer fault diagnosis -matlab code
7-18 simple simulation of banking business queue
微服务架构开源框架详情介绍
Sword finger offer 63 Maximum profit of stock
The PHP source code of the new website + remove authorization / support burning goose instead of pumping
Revit secondary development - get the project file path
6-3 find the table length of the linked table
行测-图形推理-2-黑白格类
安踏DTC | 安踏转型,构建不只有FILA的增长飞轮
Variables and constants
Unity and webgl love each other