Sub topic 4
Handling null with `?.`, `??`, `??=` and `?[]`
This chapter assumes you know basic Dart variables, functions, classes, constructors, static types, and type inference. It also assumes you can run Dart code with dart run or DartPad.
Nullable values are values whose type ends in ?, such as String? or Map<String, int>?. A nullable value can contain either an ordinary value or null. Dart provides operators that let you use these values without writing a separate if statement for every case.
Calling methods with `?.`
The null-shorting operator, ?., calls a method or reads a property only when the value before it is not null.
void main() {
String? nickname;
print(nickname?.length); // null
nickname = 'Ada';
print(nickname?.length); // 3
}When nickname is null, Dart stops at ?. and produces null. It does not call length. When nickname contains a string, Dart reads its length normally.
The result of a ?. expression is usually nullable. For example, nickname?.length has type int?, even though String.length itself returns int.
You can chain null-aware calls:
String? city;
final upper = city?.trim().toUpperCase();If city is null, the whole expression produces null. If city is not null, Dart calls both methods.
Supplying a fallback with `??`
The if-null operator, ??, chooses a fallback when its left side is null.
void main() {
String? nickname;
final label = nickname ?? 'No nickname';
print(label); // No nickname
nickname = 'Ace';
print(nickname ?? 'No nickname'); // Ace
}The right side is evaluated only when needed. This makes ?? useful for defaults, display text, configuration values, and parsed input.
You can combine ?. and ??:
String? name;
final length = name?.trim().length ?? 0;
print(length); // 0The method chain produces null when name is null. The ?? operator converts that missing result to 0.
| Expression | Meaning |
|---|---|
| `user?.name` | Read `name` only if `user` is not null |
| `value ?? fallback` | Use `fallback` when `value` is null |
| `value ??= fallback` | Assign `fallback` only when `value` is null |
| `items?[index]` | Read an item only if `items` is not null |
Assigning only when null with `??=`
The null-aware assignment operator, ??=, assigns a value only if the variable currently contains null.
void main() {
String? token;
token ??= 'temporary-token';
print(token); // temporary-token
token ??= 'another-token';
print(token); // temporary-token
}The second assignment does nothing because token already has a value. This is useful for setting a default while preserving an existing value.
??= requires a variable that can be assigned. It cannot be used with a final variable after initialization.
Indexing safely with `?[]`
The null-aware index operator, ?[], reads an index or map key only when the collection is not null.
void main() {
Map<String, int>? scores;
print(scores?['Ada']); // null
scores = {'Ada': 10};
print(scores?['Ada']); // 10
print(scores?['Lin']); // null: the map exists, but the key is absent
}A map lookup is nullable even when the map itself is non-null, because the requested key might be missing. Therefore, use ?? when the result needs a definite value.
final scores = <String, int>{'Ada': 10};
final score = scores['Lin'] ?? 0;
print(score); // 0For a nullable list, items?[0] safely handles a null list. It does not handle an invalid non-null index. If items exists but has no element at index 0, Dart still throws a range error.
Choosing the right operator
Use ?. when an operation is optional, ?? when you need a default result, ??= when you want to initialize a nullable variable once, and ?[] when the object being indexed may be null.
Exercise
What does this code print, and why? String? city; final label = city?.toUpperCase() ?? 'UNKNOWN'; print(label);
Show answer
It prints UNKNOWN. Since city is null, ?. produces null, and ?? selects the fallback string.