当前位置:网站首页>Talk about DART's null safety feature
Talk about DART's null safety feature
2022-07-07 23:01:00 【InfoQ】
Preface
null safetynull safetynull safetyNullable and non-nullable type
null satetyStringStringnull?String?nullString? str1;
String str2;
// OK
str1 = null;
// Report errors
str2 = null;
// OK
List<String?> strList1 = ['a', null, 'c'];
// Report errors
List<String> strList2 = ['a', null, 'c'];
Null assertion operator !
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 (Type promotion)
String? str;
if (str != null) {
print(str); // It has been ensured that it is not empty , No compilation errors
}
late keyword
latelate- This variable has not been assigned a value yet ;
- We will assign a value to this variable after ;
- We guarantee that we will assign a value to this variable before using it .
class Meal {
late String _decription; // Error declaration
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(' Get it done !');
}
Upgrade and modify
- Class properties : The non empty class attribute needs to be determined by the initial value by default , If the class attribute is initialized in another method , Then you can add
latekeyword , Indicates that the property will be initialized later , And it's not empty . If the property may be empty , Then add?Empty sign . This nullable attribute needs special attention when used , You need to check whether it is empty before you can use , Or usevariable?.xxAccess... In this form , If an explicit attribute has a value , You need to use ! Force specified to be non empty , Such asvariable!.xx.
- Method parameter : Set whether the parameter can be null or required as required , For mandatory parameters, add... Before the parameter declaration
requiredkeyword , Can be empty plus?identification .
- Return value : If the return value may be
null, Just add... After the return parameter?identification . If an object in the collection object is empty , Then you need to add... After the type of the collection ? identification , for exampleList<int?>.
- Will rely on the lowest Dart The version is revised to 2.12.0
environment:
sdk: ">=2.12.0 <3.0.0"
- Modify some third-party plug-in dependencies , Upgrade to support null safety edition , For details, please refer to pub Version Description on .
Dio Step on the pit
DioDioError [DioErrorType.other]: type 'Null' is not a subtype of type 'Object'issueDioCookieManagerheadersCookie_cookienull_cookieCookie// CookieManager Previous code ,_cookie May be null Lead to Dio The abnormal
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
options.headers['Cookie'] = _cookie;
return super.onRequest(options, handler);
}
// After modification
@override
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
// null safety You can set... Only if it is not empty
if (_cookie != null) {
options.headers['Cookie'] = _cookie;
}
return super.onRequest(options, handler);
}
summary
null safetynull safetyDartdynamicRequestOptions optionsheadersMap<String, dynamic>nulldynamicnull
边栏推荐
- Interview questions: how to test app performance?
- Line test - graphic reasoning - 3 - symmetric graphic class
- Pyqt GUI interface and logic separation
- 数字化转型:五个步骤推动企业进步
- Apple further entered the financial sector through the 'virtual card' security function in IOS 16
- 今日创见|企业促进创新的5大关键要素
- 关于海康ipc的几个参数
- Variables and constants
- Microservice Remote debug, nocalhost + rainbond microservice Development second Bomb
- 行测-图形推理-9-线条问题类
猜你喜欢

ASP. Net core introduction V

Line measurement - graphic reasoning -9- line problem class

Unity FAQ (I) lack of references

Visual design form QT designer design gui single form program

GBU1510-ASEMI电源专用15A整流桥GBU1510

Line test - graphic reasoning - 2 - black and white lattice class

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

Line test graph reasoning graph group class

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

Early childhood education industry of "screwing bar": trillion market, difficult to be a giant
随机推荐
Select sort (illustration +c code)
C development -- WPF simple animation
0-5vac to 4-20mA AC current isolated transmitter / conversion module
Some parameters of Haikang IPC
What is ADC sampling rate (Hz) and how to calculate it
Sword finger offer 55 - I. depth of binary tree
Sword finger offer 63 Maximum profit of stock
What does it mean to prefix a string with F?
Understand the session, cookie and token at one time, and the interview questions are all finalized
ASEMI整流桥KBPC1510的型号数字代表什么
消息队列与快递柜之间妙不可言的关系
详解全志V853上的ARM A7和RISC-V E907之间的通信方式
Variables and constants
Robot autonomous exploration DSVP: code parsing
“拧巴”的早教行业:万亿市场,难出巨头
开发那些事儿:Go加C.free释放内存,编译报错是什么原因?
Install mxnet GPU version
ADC采样率(HZ)是什么怎么计算
Basic knowledge of binary tree
ASP.NET Core入门五