Null Aware Operators in Dart Programming


Dart has different null aware operators that we can use to make sure that we are not accessing the null values and to deal with them in a subtle way.

Mainly, these are −

  • ?? operator

  • ??= operator

  • ? operator

We will go through each of them in the following article.

?? operator

The ?? operator returns the first expression if and only if it is not null.

Example

Consider the example shown below −

void main() {
   var age;
   age = age ?? 23;
   print(age);

   var name = "mukul";
   name = name ?? "suruchi";
   print(name);
}

In the above example, we declared two variables and one of them is of null value and the other is not null and contains a string value. We are using the ?? operator when reassigning values to those variables. In the first variable, since the age is null, the ?? operator will return the second value, i.e., 23 and in the second case, the name variable is not null, hence the first value will be returned from the ?? operator.

Output

23
mukul

??= operator

The ??= operator in Dart is used when we want to assign a value if and only if it is not null.

Example

Consider the example shown below −

void main() {
   var age;
   var myAge = 24;
   myAge ??= age;
   print(myAge);
}

In the above example we have two variables, one of them is null and the other contains an int value, when we try to assign the value of the age variable to myAge variable it did nothing, as age is null and hence the ??= doesn't change the original value of myAge variable.

Output

24

? operator

The ? operator is used when we want to make sure that we don't invoke a function of a null value. It will call a function if and only if the object is not null.

Example

Consider the example shown below −

void main() {
   var earthMoon;
   var length = earthMoon?.length;
   print(length);
}

In the above code, we know that the variable earthMoon has null as its value, so when we try to invoke the length function on it using the ? operator nothing changed, and the length variable is also a null value.

Output

null

Updated on: 24-May-2021

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements