This tutorial shows you what kind of null-aware operators available in Dart and how to use them.
Some programming languages already have null-aware operators. Those operators make it easier for us write code as we need shorter code for checking null
value. Dart has several operators like that as listed below.
Double Questions (??
) Mark
For example, there are two functions.
int func1() {
return 1;
}
int func2() {
return 2;
}
We want to use the result from the func1
. But if it returns null
, switch to use the result of another function func2
. That can be achieved with the code below:
int result = func1() ?? func2();
print('Result: $result');
which is equivalent to
int result = func1();
if (result == null) {
result = func2();
}
print('Result: $result');
Double Questions + Equal (??=
) Mark
How to assign to a variable only if it's null
. For example, we want to assign value
with defaultValue
only if value
is null
.
int value = null;
int defaultValue = 1;
You can use the following:
value ??= defaultValue;
print('Value: $value');
The code above is the same as:
if (value == null) {
value = defaultValue;
}
print('Value: $value');
Question + Dot (?.
) Mark
If you want to access an attribute or a method only if the object is not null
, you can use this operator.
For example, there are two classes: Category
and Item
.
class Category {
String name;
Category({this.name});
}
class Item {
int id;
String name;
Category category;
Item({this.id, this.name, this.category});
}
To get the name
value of an Item
class, normally we would write item.name
. However, if item
is null
, NoSuchMethodError
will be thrown.
This operator can be used to avoid that exception. If item
is null
, it will return null
instead of throwing the exception.
Item item = new Item(name: 'Item one');
String name = item?.name;
print('Name: $name');
Creating a chain of ?.
is also supported. The below example is for getting the category name. It will be save if the item
or its category
is null
.
Item item = new Item(name: 'Item one', category: new Category(name: 'Cat 1'));
String name = item?.category?.name;
print('Category Name: $name');
Triple Dot + Question (...?) Mark
It's an operator introduced in Dart 2.3. The triple dot is used to expand collections. However, it will throw exception when applied on a null
Collection
.
List<int> l1 = [1, 2, 3];
List<int> l2 = null;
List<int> l3 = [...l1, ...?l2];
By adding ?
, it will be safe if the Collection
is null
Without that operator, you have to write like this:
List<int> l3 = l1;
if (l2 != null) {
l3.addAll(l2);
}