当前位置:网站首页>聊聊 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 - operation family documents
- Unity technical notes (II) basic functions of scriptableobject
- C # Development -- pit encountered in JS intermodulation
- XMIND mind mapping software sharing
- Why is network i/o blocked?
- What is ADC sampling rate (Hz) and how to calculate it
- Leetcode1984. Minimum difference in student scores
- This time, let's clear up: synchronous, asynchronous, blocking, non blocking
- 肠道里的微生物和皮肤上的一样吗?
- Revit secondary development - Hide occlusion elements
猜你喜欢

Knowledge drop - PCB manufacturing process flow
![Leetcode interview question 02.07 Linked list intersection [double pointer]](/img/a5/58b4735cd0e47f1417ac151a1bcca4.jpg)
Leetcode interview question 02.07 Linked list intersection [double pointer]

【测试面试题】页面很卡的原因分析及解决方案

How pyGame rotates pictures

CTF练习

Redis集群安装

微生物健康网,如何恢复微生物群落

There is another problem just online... Warm

双非大厂测试员亲述:对测试员来说,学历重要吗?

How to choose the appropriate automated testing tools?
随机推荐
Aspose. Words merge cells
Leetcode1984. Minimum difference in student scores
Revit secondary development - intercept project error / warning pop-up
行测-图形推理-1-汉字类
C # realizes the communication between Modbus protocol and PLC
[environment] pycharm sets the tool to convert QRC into py file
数字化转型:五个步骤推动企业进步
Visual design form QT designer design gui single form program
Quick sort (diagram +c code)
Nx10.0 installation tutorial
Revit secondary development - link file collision detection
Revit secondary development - Hide occlusion elements
【测试面试题】页面很卡的原因分析及解决方案
Sword finger offer 55 - I. depth of binary tree
Revit secondary development - get the project file path
Microbial Health Network, How to restore Microbial Communities
IP network active evaluation system -- x-vision
The author of LinkedList said he didn't use LinkedList himself
Matplotlib quick start
Robot autonomous exploration DSVP: code parsing