Sub topic 11
Null-check patterns with Dart 3
This chapter assumes you know the difference between T and T?, the null-aware operators (?., ??), and promotion after if (x != null). You should also know basic Dart 3 syntax such as records. The chapter shows how a pattern can test for null and bind a non-nullable variable in one step.
What a null-check pattern is
Dart 3 added patterns. A pattern describes the shape of a value, and when the value fits, the pattern can pull parts out of it into new variables. One of the simplest patterns is the null-check pattern, which is a subpattern followed by ?.
void greet(String? name) {
if (name case final n?) {
print('Hello, $n');
} else {
print('Hello, stranger');
}
}
void main() {
greet('Ada'); // Hello, Ada
greet(null); // Hello, stranger
}Here name case final n? reads as: "if name is not null, match the rest of the pattern against it". The rest of the pattern is final n, which declares a variable. Its type is String, not String?, because the pattern only succeeds for non-null values.
There are two parts to remember:
- The
?fails the match when the value isnull. - The inner pattern runs on the non-null value, and its variable gets the non-nullable type.
The ? here is not the ?. operator and not the ? : conditional. It appears only inside a pattern, directly after a subpattern.
Where patterns can appear
You can use null-check patterns anywhere Dart accepts a pattern:
- An
ifstatement withcase, as above. - A
switchstatement. - A
switchexpression. - A variable declaration, such as
var (a, b) = ....
Each of these accepts the same pattern syntax, so what you learn for if-case carries over.
Switch expressions and exhaustiveness
A switch on a nullable value must handle null. The compiler checks this, which is called exhaustiveness checking. A null-check pattern lets you cover every non-null value in one case.
String label(int? score) => switch (score) {
null => 'no score',
final s? when s >= 90 => 'excellent $s',
final s? when s >= 50 => 'pass $s',
final s? => 'fail $s',
};
void main() {
print(label(95)); // excellent 95
print(label(60)); // pass 60
print(label(10)); // fail 10
print(label(null)); // no score
}The null case is a constant pattern that matches only null. The cases with final s? match every non-null int. The when clause adds a guard, which is a boolean condition checked after the pattern matches. Inside the guard and the result, s is an int, so s >= 90 needs no extra check.
The last case, final s? without a guard, makes the switch exhaustive. If you removed it, the compiler would report that the switch does not cover all possible values, because guarded cases do not count toward exhaustiveness. This is the main benefit over a chain of if statements: the compiler tells you when you forget a case.
Flow of a null-check match
The diagram shows what the runtime does when it tests one case that uses pattern?.
Comparing `if-case` with a plain null check
You already have two ways to handle a nullable local variable: an if (x != null) check that promotes it, and the ?? operator. A null-check pattern adds a third option. These are the differences:
| Approach | Introduces a new variable | Variable usable after the `if` | Works on fields and getters |
|---|---|---|---|
| `if (x != null)` | No, promotes the existing local | Yes, with an early return | Only for local variables |
| `x ?? fallback` | No | Not applicable | Yes |
| `if (x case final v?)` | Yes, `v` | No, only in the matched branch | Yes |
The last column is where patterns help most. A mutable field cannot be promoted, because another piece of code could change it between the check and the use. A pattern reads the field once and binds the result to a local variable.
class Account {
String? nickname;
}
void show(Account account) {
if (account.nickname case final nick?) {
print('Nickname: ${nick.toUpperCase()}');
} else {
print('No nickname');
}
}
void main() {
show(Account()..nickname = 'ace'); // Nickname: ACE
show(Account()); // No nickname
}This does the same job as the "copy to a local variable" workaround for fields, but in one line and with a name scoped to the branch.
The binding lives only in the matched branch
A variable bound in an if-case exists only inside the then branch. You cannot use the early-return style that works with != null:
int lengthOrZero(String? s) {
if (s == null) return 0;
return s.length; // s is promoted here, after the if
}With if-case the equivalent is to put the work inside the branch, or to use a switch expression:
int lengthOrZero(String? s) => switch (s) {
final v? => v.length,
null => 0,
};
void main() {
print(lengthOrZero('abc')); // 3
print(lengthOrZero(null)); // 0
}Use the one that keeps the code shortest. For a single early exit, the plain if (s == null) return is usually clearer.
The null-assert pattern
The null-check pattern has a sibling, the null-assert pattern, written pattern!. It does not fail the match when the value is null. It throws a runtime error instead, like the ! operator you met earlier.
(int?, String?) load() => (7, 'Ada');
void main() {
final (id!, name!) = load();
print(id + 1); // 8
print(name.toUpperCase()); // ADA
}Here id and name are declared as int and String. If load() returned null in either position, the destructuring would throw a TypeError.
| Pattern | Value is null | Value is not null |
|---|---|---|
| `v?` | The match fails quietly | Matches, `v` is non-nullable |
| `v!` | Throws at runtime | Matches, `v` is non-nullable |
| `null` | Matches | The match fails quietly |
| `String v` | The match fails quietly | Matches if the value is a `String` |
The choice follows the same rule as the ! operator. Use ? when null is a legitimate case you handle. Use ! only when null means a bug, and you would rather crash early than continue with bad data.
Type patterns reject null too
A typed variable pattern such as String name already excludes null when the matched value is Object?. This is why a type test is often enough when you destructure data of unknown shape, such as decoded JSON:
String describe(Map<String, Object?> json) {
if (json case {'name': String name, 'email': String email}) {
return '$name <$email>';
}
if (json case {'name': String name}) {
return name;
}
return 'unknown';
}
void main() {
print(describe({'name': 'Ada', 'email': '[email protected]'}));
// Ada <[email protected]>
print(describe({'name': 'Ada', 'email': null})); // Ada
print(describe({})); // unknown
}Three behaviors matter in this example:
- A map pattern matches only if the key exists. A missing key makes the match fail.
String emailfails when the value isnull, so the firstifis skipped for the second input.- You do not need
String email?. The type test already implies non-null.
Add ? only when the value's static type is nullable and you do not want to test for a specific type. If you want to accept both a String and null for a key, use the type String? as the pattern: {'email': String? email}. This binds email as nullable and matches either case, as long as the key is present.
Common mistakes
- Expecting the binding after the
if. The variable exists only in the matched branch. Move the code that uses it into that branch. - Forgetting the null case in a switch. Without a
nullcase or a?pattern, a switch on a nullable value fails exhaustiveness checking. Guarded cases alone do not satisfy the check. - Using
!as a shortcut.final (id!, name!) = load();is concise but crashes on null. If a missing value is possible, handle it with?. - Over-using patterns for simple cases.
name ?? 'stranger'is shorter than a switch for a plain default. - Mixing up
?meanings. A trailing?on a type makes it nullable (String?), a?after a subpattern is a null-check, and?.is the null-aware access operator.
Putting it together
The next example combines several ideas: a record with nullable fields, a switch expression, a null-check pattern with a guard, and the null constant pattern.
String summarize((String?, int?) entry) => switch (entry) {
(null, null) => 'empty',
(final name?, null) => '$name (age unknown)',
(null, final age?) => 'anonymous, $age',
(final name?, final age?) when age < 18 => '$name, minor',
(final name?, final age?) => '$name, $age',
};
void main() {
print(summarize((null, null))); // empty
print(summarize(('Ada', null))); // Ada (age unknown)
print(summarize((null, 30))); // anonymous, 30
print(summarize(('Bo', 12))); // Bo, minor
print(summarize(('Ada', 36))); // Ada, 36
}The compiler verifies that all four combinations of null and non-null are covered, because the last case has no guard. If you delete the (null, final age?) case, the compiler reports the missing combination. A chain of if (a != null && b != null) checks cannot give you that guarantee.
Exercise
What is the static type of n inside the body of if (value case final n?) when value has type double?, and what happens when value is null?
Show answer
n has type double, not double?. When value is null, the pattern does not match, so the if body is skipped and the else branch (if any) runs. No error is thrown.
Exercise
Complete this function so it compiles and is exhaustive, returning the string length for a non-null value and -1 for null: int measure(String? text) => switch (text) { // your cases here };
Show answer
One correct answer is:
int measure(String? text) => switch (text) {
null => -1,
final t? => t.length,
};
Both cases are needed. The null case matches null, and final t? matches every non-null String and binds it as a non-nullable variable.
Exercise
A class has a mutable field String? title. Write an if statement using a pattern that prints the title in upper case only when it is not null, without using the ! operator.
Show answer
if (post.title case final t?) { print(t.toUpperCase()); } The pattern reads the field once and binds it to the local variable t, which is a String. This avoids the field promotion problem because the check and the use work on the same local copy.