Today I Learned
Search…
Null aware operators in Dart
Posted on 7 Nov, 2021
Null aware operators makes handling real world data very intuitive & easy. Let's have a brief overview of all the 4 null aware operators in Dart.

The ?. operator

Prevent method call on null objects
1
// call func() only if myVar is not null
2
myVar?.func();
3
// can also be chained
4
final value = myVar?.getValue()?.valueA;
Copied!
This is similar to following code
1
myVar = myVar == null ? null : myVar.func();
Copied!

The ?? operator

This operator can be used to assign a default fallback value.
Return the first expression IFF it is not null.
1
// if unkownSource is null assign username with "default value" otherwise assign the value of unkownSource
2
username = unkownSource ?? "default value";
Copied!

The ??= operator

Assign a value IFF it is not null.
1
// assign string "test" to myVar only if myVar is null
2
myVar ??= "test";
Copied!

The ...? operator - Null aware spread operator

Expand list elements IFF it's not null
1
void main() {
2
List<int> varA = [2, 3, 4];
3
List<int>? varB = null;
4
final concatList = [1, ...varA, ...?varB];
5
print(concatList);
6
// [1, 2, 3, 4]
7
}
Copied!