Sub topic 4
Handling null with ?., ??, ??= and ?[]
This chapter assumes you know basic Dart syntax, understand the difference between T and T?, and can run code with dart run or in DartPad. Once a value has a nullable type, the compiler stops you from using it as if it could never be null. Four operators let you handle that case without writing an if statement every time: ?., ??, ??= and ?[]. A fifth, ...?, applies the same idea to spreading collections.
The operators at a glance
| Operator | Name | What it does | Result type |
|---|---|---|---|
| `a?.b` | Null-aware access | Reads `b` if `a` is not null, otherwise gives `null` | Nullable version of `b`'s type |
| `a ?? b` | If-null | Gives `a` if it is not null, otherwise `b` | Type of `a` without `?`, joined with `b`'s type |
| `a ??= b` | Null-aware assignment | Assigns `b` to `a` only if `a` is null | Same as `a ?? b` |
| `a?[i]` | Null-aware index | Reads `a[i]` if `a` is not null, otherwise gives `null` | Nullable version of the element type |
| `...?a` | Null-aware spread | Inserts the elements of `a` if it is not null, otherwise nothing | Not an expression; used inside collection literals |
Null-aware access: ?.
The ?. operator checks the receiver (the value on its left) before touching a member. If the receiver is null, the whole expression evaluates to null and the member is never accessed.
void main() {
String? nickname;
print(nickname?.length); // null
nickname = 'Ace';
print(nickname?.length); // 3
}The type of nickname?.length is int?, not int. The result is nullable because the expression might produce null, even though length itself is never null. You still have to deal with that int? afterward, usually with ?? or a null check.
?. works on method calls too: nickname?.toUpperCase() returns String?. It also works for setters: user?.name = 'Ada' assigns only if user is not null.
Short-circuiting
When the receiver is null, Dart skips the rest of the selector chain, not just the next member. This lets you write a single ?. where you might expect several.
class Profile {
final String name;
Profile(this.name);
}
class Account {
final Profile profile;
Account(this.profile);
}
void main() {
Account? account;
// Only the first dot needs the question mark. If account is null,
// the whole chain stops and the result is null.
String? name = account?.profile.name;
print(name); // null
}Short-circuiting also skips argument evaluation. In the next example, next() is never called because the receiver is null.
int counter = 0;
int next() => ++counter;
void main() {
String? text;
text?.padLeft(next());
print(counter); // 0, the argument was never evaluated
}You only need ?. at the points in a chain where a value can actually be null. Adding it after a non-nullable member produces an analyzer warning, because the check can never succeed.
Members that exist on null
A few members are defined on Object, so every value has them, including null: toString(), hashCode, == and runtimeType. You can call them on a nullable value without ?..
void main() {
int? maybe;
print(maybe.toString()); // null
print(maybe.hashCode); // 2011 (an arbitrary but valid hash)
}The exact hash value can differ between Dart versions. Do not depend on it.
If-null: ??
The ?? operator provides a fallback. It evaluates its left side, and if that is not null it uses it. Only then does it skip the right side. The right side is evaluated lazily, so it can safely be an expensive call or something with side effects.
String describe(String? nickname) => nickname ?? 'anonymous';
void main() {
print(describe('Ace')); // Ace
print(describe(null)); // anonymous
}The most common pattern combines ?. and ??: read through a possibly null chain, then supply a default for the null case.
class User {
final String? email;
User({this.email});
}
void main() {
User? user;
final label = user?.email ?? 'no email';
print(label); // no email
}Here user?.email is String?, and ?? 'no email' turns it into a plain String. After the ??, label is non-nullable.
Precedence
?? has lower precedence than arithmetic operators. That means a ?? 0 + 1 parses as a ?? (0 + 1), which is rarely what you want. Add parentheses when you mix them.
void main() {
int? a;
print((a ?? 0) + 1); // 1
a = 5;
print(a ?? 0 + 1); // 5, because the right side (0 + 1) was never used
}Do not use ?? on a non-nullable left side
If the left side can never be null, the right side is dead code. The analyzer reports a warning, so treat that warning as a sign your types and your logic disagree.
Null-aware assignment: ??=
The ??= operator assigns only when the variable is currently null. It is shorthand for a = a ?? b, except that a is evaluated once and the assignment is skipped entirely when a already has a value.
void main() {
String? name;
name ??= 'guest';
print(name); // guest
name ??= 'other';
print(name); // guest, because name was already set
}It is useful for defaults and for caching. With a Map, the lookup returns null for a missing key, so ??= fills in missing entries.
final cache = <String, int>{};
int expensive(String key) {
print('computing $key');
return key.length;
}
void main() {
print(cache['abc'] ??= expensive('abc')); // computing abc, then 3
print(cache['abc'] ??= expensive('abc')); // 3 only
}The second call does not print computing abc, because the map already contains the key. The right side runs only when needed.
A final variable cannot be assigned with ??= once it has a value, and a non-nullable variable never needs it, since it can never be null.
Null-aware index: ?[]
The ?[] operator does for subscripts what ?. does for members. If the collection is null, the result is null.
void main() {
List<int>? scores;
print(scores?[0]); // null
scores = [10, 20];
print(scores?[0]); // 10
Map<String, int>? ages;
print(ages?['ann']); // null
}It also works on the left side of an assignment. The assignment is skipped if the collection is null.
void main() {
List<int>? scores;
scores?[0] = 99; // does nothing
print(scores); // null
}Be careful about what ?[] does not do. It guards against a null collection, not against a bad index. On a non-null list, an out-of-range index still throws.
void main() {
final scores = <int>[10, 20];
// print(scores?[5]); // RangeError: the list is not null, the index is invalid
print(scores.length > 5 ? scores[5] : null); // null
}Also remember that a Map lookup like ages['ann'] returns V? even on a non-null map, because the key may be missing. Chapter 10 covers this in detail.
Spreading with ...?
Inside a list, set or map literal, ... inserts every element of another collection. If that collection might be null, use ...? and a null value contributes nothing.
void main() {
final base = <int>[1, 2];
List<int>? extra;
print([...base, ...?extra]); // [1, 2]
extra = [3];
print([...base, ...?extra]); // [1, 2, 3]
}Plain ... on a nullable collection is a compile-time error, so the compiler makes you decide.
Null-aware cascades
A cascade (..) runs several operations on the same object. If the target might be null, start the cascade with ?.. and the whole cascade is skipped when the target is null.
void main() {
StringBuffer? buffer;
buffer?..write('a')..write('b');
print(buffer); // null
buffer = StringBuffer();
buffer?..write('a')..write('b');
print(buffer); // ab
}Only the first operator needs the question mark. Later .. operators in the same cascade are covered by it.
How evaluation flows
The diagram shows what happens for user?.email ?? 'no email'.
Both paths end in a plain String. That is the point of pairing ?. with ??: the first produces a possibly null value, the second removes the possibility.
Common mistakes
- Treating the result of
?.as non-nullable.s?.lengthisint?. Passing it where anintis required fails to compile. Add?? 0, a null check, or restructure. - Using
?.everywhere "to be safe". Extra question marks on values that cannot be null trigger warnings and hide where nulls really come from. Put them only where the type is nullable. - Hiding bugs behind defaults.
value ?? 0makes the error disappear, but a missing value may deserve an error or a visible state instead of a silent zero. Choose defaults that make sense for the domain. - Expecting
?[]to prevent aRangeError. It only checks the collection for null. - Forgetting precedence with
??. Parenthesize when you combine it with+,-,*or comparisons. - Using
??=on something other than a variable, field, or index target. The left side must be assignable. You cannot writecompute() ??= 3.
Exercise
What are the types of a and b in String? text; final a = text?.length; final b = text?.length ?? 0;, and does text?.length call anything when text is null?
Show answer
a is int? and b is int. When text is null, ?. short-circuits: length is not read and the expression evaluates to null. The ?? 0 then supplies the fallback, which is why b is non-nullable.
Exercise
Given Map<String, List<int>>? groups;, write a single expression that returns the first number of the list for key 'a', or -1 if the map is null, the key is missing, or the list is empty. Why is groups?['a']?[0] ?? -1 not enough?
Show answer
groups?['a']?[0] ?? -1 handles a null map and a missing key, but if the list exists and is empty, [0] throws a RangeError, because ?[] only checks for null. A safe version is (groups?['a']?.firstOrNull) ?? -1, using the firstOrNull getter from dart:core (Dart 3.0 and later), which returns null for an empty list.