Sub topic 6
Letting the compiler check every case
This chapter assumes you can read Dart 3 switch expressions and object patterns, and that you have the LoadState hierarchy from the earlier chapters. Here you will see how the compiler decides that a switch is complete, what breaks that guarantee, and how to keep it intact as your app grows.
What exhaustiveness means
A switch is exhaustive when the compiler can prove that every possible value of the matched type is handled by at least one case. Dart 3 requires this for switch expressions. It also requires it for switch statements that use patterns, or that match an enum, a sealed type, or a bool. If the proof fails, the code does not compile.
This is why a sealed class is useful. A sealed class has a closed set of direct subtypes, all in one library, so the compiler knows the full list. It can then compare that list with your cases.
sealed class LoadState<T> {
const LoadState();
}
final class Loading<T> extends LoadState<T> {
const Loading();
}
final class Loaded<T> extends LoadState<T> {
const Loaded(this.data);
final T data;
}
final class Failed<T> extends LoadState<T> {
const Failed(this.error);
final Object error;
}
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
Failed(error: final e) => 'Error: $e',
};
void main() {
print(describe(const Loading()));
print(describe(const Loaded(['a', 'b'])));
print(describe(Failed(StateError('boom'))));
}Running this prints Loading..., 2 items, and Error: Bad state: boom. There is no default branch, and none is needed. The three cases cover every subtype of LoadState.
How the check works
The compiler treats the matched type as a space of values. Each case removes part of that space. If nothing is left after the last case, the switch is exhaustive.
The unguarded-case rule has a consequence that surprises many people. It is covered in its own section below.
The payoff: adding a variant
Suppose the product team wants to keep showing old data while a refresh runs. You add a fourth subtype.
final class Refreshing<T> extends LoadState<T> {
const Refreshing(this.previous);
final T previous;
}Every switch over LoadState that lacks a Refreshing() case now fails analysis. The error names the missing case, in the form "The type 'LoadState<List<String>>' is not exhaustively matched by the switch cases since it doesn't match 'Refreshing()'." Your editor underlines the switch, and dart analyze and flutter analyze list every location. You fix each switch by adding a case:
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
Refreshing(previous: final items) => 'Refreshing ${items.length} items',
Failed(error: final e) => 'Error: $e',
};With a flag-based design, the same change would have been a runtime bug that someone found in testing or after release. Here it is a list of compile errors.
Wildcards and defaults switch the check off
A _ pattern or a default clause matches everything, so after it nothing is left to check. The compiler stops warning you about new variants.
bool isBusy(LoadState<List<String>> state) => switch (state) {
Loading() => true,
_ => false,
};This compiles before and after you add Refreshing. After the change it returns false for a refreshing screen, which is probably wrong, and no tool tells you. List the variants instead:
bool isBusy(LoadState<List<String>> state) => switch (state) {
Loading() || Refreshing() => true,
Loaded() || Failed() => false,
};The || between patterns is a logical-or pattern. It lets two variants share one result without a wildcard.
A wildcard is fine on the last line of a switch over an open type such as int or String, where exhaustiveness cannot be proven any other way.
Guarded cases do not count
A when clause makes a case depend on a runtime condition. The compiler does not evaluate arbitrary expressions, so it assumes a guarded case might not match. A guarded case therefore contributes nothing to coverage.
// Does not compile: no unguarded Loaded case exists.
String label(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) when items.isNotEmpty => '${items.length} items',
Failed() => 'Error',
};The analyzer reports that Loaded() is not matched, even though you may feel the guard covers the interesting case. The fix is a fallback case for the same variant, placed after the guarded one:
String label(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) when items.isEmpty => 'Nothing here yet',
Loaded(data: final items) => '${items.length} items',
Failed() => 'Error',
};Cases are tried from top to bottom, and the first match wins. Put guarded cases before the unguarded case for the same variant. If you reverse them, the analyzer reports the guarded case as unreachable, because the earlier case already matches everything.
What the compiler can and cannot enumerate
Sealed classes are one of several types the compiler knows how to enumerate.
| Matched type | What counts as exhaustive |
|---|---|
| Sealed class | A case for every direct subtype, or patterns that together cover each one |
| Enum | A case for every enum value |
| `bool` | Cases for `true` and `false` |
| Nullable type `T?` | Cases that cover `T`, plus a `null` case |
| Record | Every combination of the fields' possibilities |
| `int`, `String`, open classes | Never, unless a wildcard or catch-all variable pattern is present |
Nullability follows the same rule. If a value has the type LoadState<int>?, you must also handle null:
String describeMaybe(LoadState<int>? state) => switch (state) {
null => 'No request made',
Loading() => 'Loading...',
Loaded(data: final n) => 'Got $n',
Failed(error: final e) => 'Error: $e',
};Exhaustiveness also applies recursively. A subtype that is itself sealed is checked through its own subtypes, and the checks combine across the fields of a record or object pattern. The next example matches on a record of two booleans and is exhaustive without a wildcard:
String access({required bool signedIn, required bool premium}) =>
switch ((signedIn, premium)) {
(false, _) => 'Sign in',
(true, false) => 'Free tier',
(true, true) => 'Premium',
};The (false, _) case covers both values of premium when signedIn is false. The wildcard here is safe because premium is a closed bool. It is not hiding a future variant.
Statements and expressions
A switch expression produces a value, so every path must produce one. A switch statement runs code, and in Dart 3 it has the same exhaustiveness requirement when it matches a sealed type. A statement also lets you do nothing in a branch:
void log(LoadState<List<String>> state) {
switch (state) {
case Loading():
print('start');
case Loaded(data: final items):
print('got ${items.length}');
case Failed():
case Refreshing():
break;
}
}An empty case that falls through to the next one, as Failed() does here, shares the next case's body. Dart does not require break at the end of a case. Writing the empty branches out keeps the compile-time check. Replacing them with default: would not.
Limits worth knowing
- Same library. All direct subtypes of a sealed class must live in the same library, which is normally the same file. Code in other packages cannot add a variant, so your switches stay complete.
- Sealed classes cannot be instantiated. A sealed class is implicitly abstract. You always construct one of the subtypes.
- Declare variants as
final. Thefinal classmodifier on each subtype prevents extension outside the library, which keeps the set of possible runtime types predictable. - Exhaustiveness is checked by type, not by data. The compiler knows
Loadedis handled. It does not know thatitemsis never empty, which is why you need a guard or a fallback case for that.
Common errors
- Adding
_ =>to silence an error. This hides the problem. Add the missing case so the next variant is also caught. - Relying on guards for coverage. Add an unguarded case for each variant that appears in a guarded one.
- Forgetting
null. Matching onLoadState<T>?needs anullcase. - Putting a broad case first.
Loaded() => ...aboveLoaded(data: final items) when items.isEmpty => ...makes the second case unreachable, and the analyzer warns you.
Exercise
A teammate adds Idle as a new subclass of sealed class LoadState<T>, in the same file. Your widget has a switch expression with cases for Loading(), Loaded(), Failed(), and a final _ => const SizedBox(). What does the compiler report, and what should you change?
Show answer
The compiler reports nothing, because the _ case matches Idle and the switch is still exhaustive. The widget will silently show an empty box for Idle. Remove the _ case and add an explicit Idle() case. The analyzer will then flag every other switch over LoadState that is missing Idle().
Exercise
This function does not compile. Why, and how do you fix it? String label(LoadState<List<String>> s) => switch (s) { Loading() => 'Loading...', Loaded(data: final items) when items.isNotEmpty => '${items.length} items', Failed() => 'Error', };
Show answer
The only Loaded case has a when guard, and guarded cases do not count toward exhaustiveness, so Loaded with an empty list is unmatched. Add an unguarded Loaded(data: final items) => 'Nothing here yet' after the guarded case.