Sub topic 9
Refining a case with when
This chapter assumes you can read Dart 3 switch expressions and object patterns, and that you know the LoadState<T> sealed hierarchy (Loading, Loaded, Failed) from earlier chapters. You need Dart 3 or later to run the examples.
Patterns match on shape and type. Sometimes the shape is not enough. A Loaded state holding an empty list is still a Loaded, but you probably want to show something different for it. A guard clause adds a boolean condition to a case with the keyword when. The case matches only if the pattern matches and the condition is true.
Syntax and evaluation order
A guard goes after the pattern and before => in a switch expression. In a switch statement it goes before the :.
import 'dart:async';
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) when items.isEmpty => 'Nothing here yet',
Loaded(data: final items) when items.length > 100 => 'Over 100 items',
Loaded(data: final items) => '${items.length} items',
Failed(error: final e) when e is TimeoutException =>
'Timed out. Try again.',
Failed(error: final e) => 'Error: $e',
};
void main() {
print(describe(const Loading()));
print(describe(const Loaded([])));
print(describe(Loaded(List.generate(150, (i) => 'item $i'))));
print(describe(const Loaded(['a', 'b'])));
print(describe(Failed(TimeoutException('slow'))));
print(describe(Failed(StateError('bad'))));
}Running this prints:
Loading...
Nothing here yet
Over 100 items
2 items
Timed out. Try again.
Error: Bad state: badDart checks cases from top to bottom and runs the first one that matches. For each case it does two things in order:
- It tests the pattern. If the pattern fails, the guard is never evaluated.
- It evaluates the guard. If the guard is false, Dart moves on to the next case.
Variables bound by the pattern, such as items and e, are already in scope inside the guard. That is why items.isEmpty works without any extra lookup.
Order matters: specific before general
Because the first match wins, a guarded case must come before the unguarded case for the same variant. If you reverse them, the general case catches everything and the guarded case can never run.
String broken(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
// Unreachable: the case above already matched every Loaded.
Loaded(data: final items) when items.isEmpty => 'Nothing here yet',
Failed(error: final e) => 'Error: $e',
};The analyzer reports the last Loaded case as unreachable. Treat that warning as a bug in your ordering, not as noise. Order cases from the most specific condition to the least specific.
Guards and exhaustiveness
Exhaustiveness checking is the compiler's proof that every variant is handled. It cannot evaluate your guard expressions, because they are arbitrary code. So the compiler assumes any guarded case might not match, and it does not count that case toward covering its variant.
This means every variant that appears in a guarded case still needs an unguarded case somewhere. Here is the same function without its fallbacks:
// Does not compile.
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) when items.isEmpty => 'Nothing here yet',
Failed(error: final e) => 'Error: $e',
};The compiler reports that the switch is not exhaustive because it does not handle Loaded. This is the behavior you want. Even though isEmpty is the only condition you thought about, a non-empty list would reach the switch with no matching case and throw at runtime if the compiler allowed this.
A guard whose condition is always true, such as when true, does not help. The compiler still treats the case as guarded.
Guard or nested pattern?
Some conditions can be written as part of the pattern instead of as a guard. The choice affects readability, and sometimes how much the compiler can verify.
| Condition | Pattern form | Guard form |
|---|---|---|
| Exact value, such as a constant | `Loaded(data: [])` | `Loaded(data: final d) when d.isEmpty` |
| Runtime type of a field | `Failed(error: TimeoutException())` | `Failed(error: final e) when e is TimeoutException` |
| Comparison, such as `> 100` | `Loaded(data: final d)` with a relational pattern only works on numbers | `when items.length > 100` |
| Method call or computed value | Not possible | `when items.any((i) => i.isEmpty)` |
| Value from outside the state | Not possible | `when offline` |
Prefer the pattern form when it exists, because it is shorter and the compiler can reason about it. Use a guard when the condition needs a method call, arithmetic on a field, or a value that is not part of the matched object.
Guards that read outside values
A guard can use any variable in scope, not only the ones the pattern binds. This is useful when the right output depends on both the state and something else, such as connectivity.
String banner(LoadState<List<String>> state, {required bool offline}) =>
switch (state) {
Failed() when offline => 'You are offline',
Failed(error: final e) => 'Error: $e',
Loading() when offline => 'Waiting for a connection...',
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
};Both Failed and Loading have a guarded case and an unguarded case, so the switch is exhaustive. Loaded needs only one case.
If you find yourself passing several outside values into a switch, consider whether they belong inside the state. A Failed variant that carries an isOffline field makes the condition part of the model, and the switch can then use a pattern instead of a guard.
Alternatives and shared guards
Several patterns can share one case with ||. A guard written after such a pattern applies to the whole case, not only to the last alternative.
String hint(LoadState<List<String>> state, int retries) => switch (state) {
Loading() || Failed() when retries > 2 => 'Please try again later',
Loading() => 'Loading...',
Failed() => 'Something went wrong',
Loaded() => 'Done',
};When retries is 3 and the state is Loading, the first case matches. When retries is 0, the guard is false for both alternatives and Dart moves on.
Guards in if-case
if-case accepts a guard in the same way. The condition follows the pattern.
void printFirst(LoadState<List<String>> state) {
if (state case Loaded(data: final items) when items.isNotEmpty) {
print(items.first);
}
}An if-case has no exhaustiveness requirement, so the "every variant needs an unguarded case" rule does not apply. If the guard is false, execution continues after the if or into its else branch.
Common mistakes
- Side effects in a guard. A guard should only read. Logging, incrementing a counter, or calling a method that changes state makes the switch hard to reason about, because you must remember which guards ran. Do the work in the case body.
- Expensive guards. Guards run one after another on every evaluation. A guard that sorts a list or hits storage will run on every rebuild when used inside a widget's
buildmethod. Compute the value once before the switch, or store it in the state. - Too many guards on one variant. If one variant has five or six guarded cases, the variant probably represents several distinct states. Split it into separate subclasses so each condition becomes a type the compiler can check.
- Forgetting the fallback. The most common error is the non-exhaustive switch described above. Fix it by adding the plain
Loaded(data: final items)case after the guarded ones.
Summary of rules
- Write
whenafter the pattern. The guard sees variables the pattern binds. - Guards run only after the pattern matches, and the first matching case wins.
- Put guarded cases before the unguarded case for the same variant.
- The compiler does not count guarded cases toward exhaustiveness, so every variant needs an unguarded case.
- Prefer a nested pattern when the condition can be expressed as one. Use a guard for method calls, computed values, and outside data.
The next chapter combines these ideas with record patterns to model transitions between states, where guards and exhaustiveness checking work together.
Exercise
A teammate writes this function and gets a "not exhaustive" compile error. What is wrong, and what is the smallest change that fixes it? String label(LoadState<List<String>> state) => switch (state) { Loading() => 'Loading...', Loaded(data: final items) when items.length > 10 => 'Many items', Failed(error: final e) => 'Error: $e', };
Show answer
The only Loaded case has a guard, so the compiler assumes it might not match and does not count it as covering Loaded. A Loaded with ten or fewer items would match no case. Add an unguarded case after the guarded one, for example Loaded(data: final items) => '${items.length} items'. Do not use _, because it would also hide missing cases for variants added later.
Exercise
Write a switch expression named retryLabel that takes a LoadState<List<String>> state and an int attempts. It returns 'Give up' for a Failed state when attempts >= 3, 'Retry' for any other Failed state, 'Wait' for Loading, and 'OK' for Loaded. Why must the 'Give up' case come first?
Show answer
String retryLabel(LoadState<List<String>> state, int attempts) => switch (state) {
Failed() when attempts >= 3 => 'Give up',
Failed() => 'Retry',
Loading() => 'Wait',
Loaded() => 'OK',
};
The guarded case must come first because Dart runs the first matching case. If Failed() => 'Retry' came first, it would match every failure and the guarded case would be unreachable. The unguarded Failed() case also keeps the switch exhaustive.