当前位置:网站首页>Talk about DART's null safety feature

Talk about DART's null safety feature

2022-07-07 23:01:00 InfoQ

Preface

About  
null safety
  In fact, it's nothing new , Early on  Swift  Already supported ,Dart It's from 2.12.2 This feature is supported in version . This article is based on official documents , Have a chat  Dart  Of  
null safety
  characteristic . Official document link :
Null Safety
.

null safety
  The biggest characteristic is
The object declared by default is non empty , Unless you specify that the object can be empty
.

Nullable  and  non-nullable  type

When you choose to use  
null satety
  features , All types are non empty by default . For example, if you declare a  
String
Variable of type , That means it always contains string values . If you want one  
String
  Object can receive string values or
null
, Then you need to add... After the type declaration
?
identification , One declared as
String?
Variables of type can contain string values or  
null
.

String? 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 !

If it is determined that the return value of an object or expression has a value , Then you can use the empty assertion operator ! Force to non empty object , It can then be used to assign values to non empty objects , Or access its properties or methods , Such as  
valiable!.xx
. In this case , If for
nullable
  The object does not add !, The compiler will report an error . however , If the object itself is
null
, Add
!
Operators cause exceptions .

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)

In order to ensure the safety characteristics of air ,Dart  Flow analysis of (flow analysis) The null property has been considered . If one  nullable  Object cannot have null value , Then it will be treated as a non empty object , for example :

String? str;

if (str != null) {
 print(str); // It has been ensured that it is not empty , No compilation errors
}

late  keyword

Sometimes variables 、 Class member properties or other global variables should be non empty , But you can't assign values directly when you declare , At this time, you need to add... When declaring variables  
late
  keyword . When you declare a variable, add
late
The key word , Just tell  Dart  The following :

  • 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 .

for example , Below _description  Declare that if the compiler does not  late  Keywords will report errors .

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);
}

late
Keyword is also very helpful for handling circular references , For example, we have a team and a coach , The team and coach have mutual application . without  
late
  keyword , We can only declare as nullable, It would be awkward to use it then —— You need to add empty assertion operators everywhere or use
if
To determine if it's empty .

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(' Get it done !');
}

Upgrade and modify

When upgrading and modifying , According to the method parameters to be called 、 Return values or declared properties are processed as follows :

  • 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  
    late
    keyword , 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 use  
    variable?.xx 
    Access... In this form , If an explicit attribute has a value , You need to use ! Force specified to be non empty , Such as  
    variable!.xx
    .
  • Method parameter : Set whether the parameter can be null or required as required , For mandatory parameters, add... Before the parameter declaration
    required
    keyword , 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 example  
    List<int?>
    .

For dependence , It also needs to be modified  pubspec.yaml  file , The following modifications are included :

  • Will rely on the lowest  Dart  The version is revised to 2.12.0

environment:
 sdk: &quot;>=2.12.0 <3.0.0&quot;

  • 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

After upgrading ,
Dio
  Request an error
DioError [DioErrorType.other]: type 'Null' is not a subtype of type 'Object'
. I searched the Internet , stay  
issue
  It is mentioned in , But it has been solved . And then according to  issue  You can't try the method in , I thought about it later , First directly request Baidu web page to see if it is  
Dio
  The problem of , As a result, the request Baidu web page is normal , That means it's the code itself . Finally, locate and find   It is our  
CookieManager
  Interceptor's request  
headers
  Set up  
Cookie
  Field time , When
_cookie
by  
null
  An empty exception occurs when the . We need to check at this time , If
_cookie
Set only if it is not empty  
Cookie
.

// 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

From a coding point of view ,
null safety
Features actually increase the amount of coding work . however
null safety
It's more like a mandatory agreement , The interface or class is required to specify whether the parameter or property is empty , This simplifies collaboration , Improve the robustness of the code .

Of course , For third-party libraries, you need to be very careful , Some third-party libraries use dynamic  The occasion of the statement , at present  
Dart
  Yes  
dynamic
  Declared variables 、 Property is not null checked , This will result in an empty exception for such a declaration , For example, as mentioned above  
RequestOptions options
Of  
headers
, It's just one.  
Map<String, dynamic>
object , Use of results  
null
  An exception will be thrown during assignment . In this case, it is best to use as little as possible  
dynamic
  Statement , When calling a third party at the same time , If this is found , You need to check whether assignment is allowed  
null
.
null
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072030162596.html