Dart Null-Aware Operators
A null-aware operator is an operator that handles null safely. Dart uses these operators to read a value or to pick a fallback.
A safe read on a present value
name holds a text value, so the safe read reaches length. print shows the length 3.
void main() {
String? name = 'Ana';
print(name?.length);
}A safe read on null
name holds null, so the safe read gives null. print shows the word null.
void main() {
String? name;
print(name?.length);
}A fallback for null
name holds null, so the fallback after the two question marks is picked. print shows Guest.
void main() {
String? name;
print(name ?? 'Guest');
}No fallback for a present value
name holds a text value, so the fallback is skipped. print shows Ana.
void main() {
String? name = 'Ana';
print(name ?? 'Guest');
}An unguarded read fails
The read of length has no safe operator in front of it. The compiler stops because name might hold null.
void main() {
String? name;
print(name.length);
}Example
void main() {
String? name;
print(name?.length ?? 0);
name = 'Ana';
print(name?.length ?? 0);
}Key points
- Use ?. to read a part of a value only when the value is not null.
- A safe read with ?. gives null when the value holds null.
- Use ?? to pick a fallback value when the value on the left holds null.
- The fallback after ?? is skipped when the left value is not null.
- Use ??= to give a variable a value only when it currently holds null.
In this example, name starts with no value. The safe read gives null and the fallback gives 0, so the first print shows 0. The next line gives name the value Ana. The safe read then gives the length 3, so the last print shows 3.
Note
A null-aware operator handles null without stopping the program.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does name ?? 'Guest' give when name holds null?