当前位置:网站首页>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
边栏推荐
- Debezium series: source code reading snapshot reader
- Take full control! Create a "leading cockpit" for smart city construction
- 「开源摘星计划」Loki实现Harbor日志的高效管理
- What does it mean to prefix a string with F?
- “拧巴”的早教行业:万亿市场,难出巨头
- UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
- Robot autonomous exploration DSVP: code parsing
- Cause analysis and solution of too laggy page of [test interview questions]
- Form组件常用校验规则-2(持续更新中~)
- 每日一题——PAT乙级1002题
猜你喜欢

行测-图形推理-6-相似图形类

Line test - graphic reasoning - 4 - alphabetic class
![LeetCode142. Circular linked list II [two pointers, two methods for judging links in the linked list and finding ring points]](/img/5e/e442c8649b9123a9d9df7c0d61a564.jpg)
LeetCode142. Circular linked list II [two pointers, two methods for judging links in the linked list and finding ring points]

Line test - graphic reasoning - 1 - Chinese character class

XMIND mind mapping software sharing

行测-图形推理-5-一笔画类

Unity FAQ (I) lack of references

How pyGame rotates pictures

微生物健康網,如何恢複微生物群落

It's no exaggeration to say that this is the most user-friendly basic tutorial of pytest I've ever seen
随机推荐
Line test - graphic reasoning - 4 - alphabetic class
行测-图形推理-2-黑白格类
7-51 combination of two ordered linked list sequences
Variables and constants
LeetCode206. Reverse linked list [double pointer and recursion]
新版代挂网站PHP源码+去除授权/支持燃鹅代抽
Leetcode94. Middle order traversal of binary trees
全面掌控!打造智慧城市建设的“领导驾驶舱”
Unity 动态合并网格纹理
Understand the autograd package in pytorch
Common verification rules of form components -2 (continuously updating ~)
Matplotlib quick start
De la famille debezium: SET ROLE statements supportant mysql8
ASEMI整流桥KBPC1510的型号数字代表什么
ASP.NET Core入门五
0-5VAC转4-20mA交流电流隔离变送器/转换模块
小程序多种开发方式对比-跨端?低代码?原生?还是云开发?
一次搞明白 Session、Cookie、Token,面试问题全稿定
Apple further entered the financial sector through the 'virtual card' security function in IOS 16
Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020