Null aware in dart

Time:2021-4-7

Come to this article to show that you must want to go a step further in DART’s Grammar (not surprisingly, you are learning flutter). This article will talk about the null aware operator in dart language!

background

DART’s null aware comes fromDart 1.12Official version:
Null aware in dart

You can also have a lookOfficial website version introduction

purpose

Since there is such a new operator, it shows that it is reasonable to some extentSaved our code, makeThe code is more concise.

Since it’s calledNull-aware, indicating that the operator is specializedFor processingnullvalueWill provide null pointer related operations

Null aware in dart

Create sample object

Let’s create onePersonObject, convenient for subsequent use:

class Person{
  //Gender
  String gender;
  
  //Change of gender to female
  void changeToFemale(){
    Gender = female;
  }
}

Person person = Person();

??

When the current is null, the latter is returned

exp ?? anotherExp

Example: get user gender

When the gender attribute of a person object is null, ‘unknown’ is returned:

Method 1: basic if statement

We can use the most basic sentences to write:

String gender;
if(person.gender!=null){
    gender = person.gender;
}else{
    Gender ='unknown ';
}

Method 2: three eye operation

The trinary operator is quite easy to use

String gender =  person.gender !=null ?  person.gender  : 'unknown';

It’s much better to do it in one line than if

Best solution:??operator

Use just learned??Operator handling:

String gender =  person.gender  ?? 'unknown';

It’s so simple

??=

If obj is null, assign value to obj

obj ??= value

Example: default gender

If the gender property of the person object is null, it is assigned “male”

Let’s not use the stupid method here

person.gender  ?? = male;

?.

When obj is not null, callmethodFunction:

obj?.method()

Example: changing gender

When person is not null, change gender to female:

person?.changeToFemale();

Call it a day!

If you follow the tutorial and everything goes well, Congratulations, you’ve learned a new way to save your life!

thank

(ranking in any order)

epilogue

Original linkIf you have any questions, please reply or discuss below

More technical dry goods, welcome to visit my official websiteAVIC’s technology station

Recommended Today

OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]