Null-aware operators
- Dart course
- Beginner
- Lesson 72/116
- 5 min
Learn ??, ?. and ??= operators.
Null-aware operators
Dart offers three short operators for null handling. ?? null coalescing: name ?? 'Guest' — when name is non-null it returns name, otherwise 'Guest'.
?. null-aware access: name?.length — when name is non-null it returns the length, otherwise null. This avoids the name.length error.
??= null-aware assignment: name ??= 'Guest'; — if name is null it assigns 'Guest', otherwise leaves it. All three provide null safety concisely.
Safe access with ?.
The ?. operator safely accesses a member of a nullable value. name?.length returns the length when name is non-null, otherwise null. No exception is thrown.
This replaces name.length, which crashes when name is null. With ?. you say 'leave it null if it is null'.
The result is nullable: int? len = name?.length;. The next steps still need null-aware thinking. Chaining works too: user?.address?.city.
Practice Print with ??
Declare a String? name (starting as null). Print it with print(name ?? 'Misafir').
Starter code
void main() {
// declare a nullable variable (null)
// print with a default
}Sample solution
void main() {
String? name;
print(name ?? 'Misafir');
}Expected output
Misafir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The ?? operator
void main() {
String? name;
print(name ____ 'Misafir');
}
void main() {
String? name;
print(name ?? 'Misafir');
}
Explanation: ?? returns the right side when the left is null.
2 Match the operators
| Term | Meaning |
|---|---|
?? |
Default value |
. |
Safe access |
??= |
Assign if null |
? |
Nullable type |
3 What does name ?? 'Misafir' return?
String? name;
print(name ?? 'Misafir');- null if name is null
- 'Misafir' if name is null Correct answer
- Always name
- Always 'Misafir'
Explanation: ?? returns the right side when the left is null.