Sub topic 3
Refining a case with when
This chapter assumes you can write a sealed class hierarchy, a switch expression over it, and object patterns such as Loaded(data: final items). It uses the LoadState<T> type from earlier in the tutorial.
Narrowing a case with when
A when guard adds a condition to a pattern. The case matches only if the pattern matches and the condition is true.
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 e) => 'Error: $e',
};Cases are checked in order, so the guarded empty case comes before the general Loaded case. The compiler still checks exhaustiveness, but it does not count a guarded case as covering its variant. The unguarded Loaded case is needed for the non-empty lists.
Checking one variant with if-case
Use if (x case Pattern) when you care about one variant and can ignore the rest.
void printFirst(LoadState<List<String>> state) {
if (state case Loaded(data: final items) when items.isNotEmpty) {
print(items.first);
}
}Modelling transitions with records
Matching a record of (state, event) puts every transition in one place. The compiler checks that each combination is handled.
sealed class Event {
const Event();
}
final class Fetch extends Event {
const Fetch();
}
final class Succeeded extends Event {
const Succeeded(this.items);
final List<String> items;
}
final class Errored extends Event {
const Errored(this.error);
final Object error;
}
LoadState<List<String>> reduce(LoadState<List<String>> state, Event event) =>
switch ((state, event)) {
(_, Fetch()) => const Loading(),
(Loading(), Succeeded(items: final items)) => Loaded(items),
(Loading(), Errored(error: final e)) => Failed(e),
(Loaded() || Failed(), Succeeded() || Errored()) => state,
};Because reduce is a plain function with no side effects, you can test it directly.
import 'package:test/test.dart';
void main() {
test('a fetch clears an earlier error', () {
final next = reduce(Failed('timeout'), const Fetch());
expect(next, isA<Loading<List<String>>>());
});
}Same-library rule and wildcard pitfalls
Direct subtypes of a sealed class must be declared in the same library. Dart 3 rejects a subclass in another file that does not use part. Keep each state hierarchy in one file, or split it across part files of one library.
A wildcard _ => case silences the exhaustiveness check. When you later add a variant, the compiler no longer reports the switches that need updating. Prefer listing every variant. Use _ only where a new variant truly should fall through.
Choosing a modelling tool
| Option | Use when | Limitation |
|---|---|---|
| Enum | States carry no data | Cannot hold per-state fields |
| Sealed classes | States carry different data and you want no code generation | More boilerplate for copies and equality |
| Generated union | You want `copyWith`, equality, or JSON from a generator | Adds a build step and a dependency |
> Hmm, plain prose is preferred here; see the note below.
Exercise
Exercise
The reduce function above has no Event case for a retry after a failure. If you add final class Retried extends Event with no fields, which code fails to compile, and what does the error tell you?
Show answer
The switch expression in reduce fails with a non-exhaustive error, because the (state, event) combinations for Retried are not covered. Add (_, Retried()) => const Loading(), or a more specific case. The compiler reports the gap because the switch has no wildcard that would hide it.