Sub topic 9
Refining a case with `when`
Assume you know Dart classes, generics, null safety, sealed classes, and basic pattern matching. This chapter focuses on one detail: using a when guard to refine a pattern after it matches. The examples require Dart 3 or later.
Why a guard is useful
A sealed state type describes broad alternatives. For example, a loaded screen can contain either a non-empty list or an empty list. Both values have the same type, Loaded<List<String>>, but the UI usually needs different messages.
You could put this condition inside the case body. A when guard keeps the condition beside the pattern instead:
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) => '${items.length} items',
Failed(error: final error) => 'Error: $error',
};
void main() {
print(describe(const Loading<List<String>>()));
print(describe(const Loaded<List<String>>([])));
print(describe(const Loaded<List<String>>(['Tea', 'Coffee'])));
print(describe(const Failed<List<String>>('Network unavailable')));
}The object pattern Loaded(data: final items) first checks that the value is a Loaded object and binds its data field to items. The when items.isEmpty condition then decides whether that case applies.
If the guard is false, matching continues with the next case. Therefore, the empty-list case must appear before the general loaded case. The general case also handles non-empty lists.
| Pattern | Guard | Result |
|---|---|---|
| `Loading()` | none | Loading message |
| `Loaded(data: final items)` | `items.isEmpty` | Empty message |
| `Loaded(data: final items)` | none | Item count |
| `Failed(error: final error)` | none | Error message |
How matching proceeds
Dart evaluates a switch from top to bottom:
A guard can contain any Boolean expression that is valid for the values bound by the pattern. For example:
String classify(LoadState<List<String>> state) => switch (state) {
Loaded(data: final items) when items.length > 100 => 'Large result',
Loaded(data: final items) when items.isNotEmpty => 'Has results',
Loaded() => 'Empty result',
Loading() => 'Still loading',
Failed() => 'Could not load',
};The cases are ordered from most specific to most general. A list with 101 items satisfies both loaded guards, so the first case wins.
`when` with Flutter widgets
A guarded case can return a widget just like any other switch case:
Widget buildResult(LoadState<List<String>> state) {
return switch (state) {
Loading() => const CircularProgressIndicator(),
Loaded(data: final items) when items.isEmpty =>
const Text('No results'),
Loaded(data: final items) => Text('${items.length} results'),
Failed(error: final error) => Text('Error: $error'),
};
}Keep guards focused on properties of the matched value. If a condition needs network access, changes state, or performs several actions, calculate that information before the switch or move the decision into a separate function.
Exercise
What happens when a non-empty Loaded state reaches Loaded(data: final items) when items.isEmpty?
Show answer
The pattern matches, but the guard is false, so Dart continues to the next switch case.