Sub topic 11
Modelling transitions with (state, event) records
Earlier chapters built a sealed LoadState and mapped it to widgets. This chapter covers how the state changes. You write one function that takes the current state and an event and returns the next state. A switch over a record of both values lets the compiler check every combination.
This chapter assumes you know the following:
- Dart 3 sealed classes and switch expressions.
- Object patterns such as
Loaded(data: final items). - Generic classes.
You don't need Flutter to run the code. The reducer is plain Dart.
Why match on a pair
A transition depends on two things: where you are and what just happened. Two common ways to write this lose compiler help:
- A method on each state class, such as
Loading.onEvent(Event e). The rules for one event end up spread over several files. - A nested
ifchain or two nested switches. These are easy to leave incomplete, and the compiler can't see the gaps.
A switch over the record (state, event) puts every rule in one table. Because both LoadState and Event are sealed, Dart can check that every pair is covered.
Declaring events
Events are also a sealed hierarchy. Each event carries only the data it needs.
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;
}Events describe what happened (Succeeded), not what to do (ShowList). The reducer decides what the state becomes.
The reducer
This file is complete. Save it as reducer.dart and run dart run reducer.dart.
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;
}
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,
};
void main() {
LoadState<List<String>> state = const Loaded(['a', 'b']);
final events = <Event>[
const Fetch(),
const Succeeded(['x']),
const Errored('late'),
];
for (final event in events) {
state = reduce(state, event);
print('${event.runtimeType} -> ${state.runtimeType}');
}
}The output is:
Fetch -> Loading<List<String>>
Succeeded -> Loaded<List<String>>
Errored -> Loaded<List<String>>The last line shows a design choice. An Errored event that arrives after the load has already succeeded is ignored, and the state stays Loaded. This usually happens when a slow request finishes after a newer one.
Reading the four arms
The expression (state, event) builds a record, which is a fixed-size group of values. Each arm is a record pattern with one sub-pattern per position.
| Arm | Meaning | Column | Column | Column | Column |
|---|---|---|---|---|---|
| `(_, Fetch())` | Any state plus a fetch request goes to `Loading`. | ||||
| `(Loading(), Succeeded(...))` | A result arrives while loading, so show the data. | ||||
| `(Loading(), Errored(...))` | A failure arrives while loading, so show the error. | ||||
| `(Loaded() \ | \ | Failed(), Succeeded() \ | \ | Errored())` | A result arrives when none is expected, so keep the current state. |
The last arm uses the || pattern to join alternatives. It covers four combinations in one line.
The diagram leaves out the ignored combinations (a result event while Loaded or Failed), because those arms leave the state unchanged. The switch makes you write them down anyway.
What the compiler checks
Each of the two sealed types splits into variants. Dart treats the record's space as every combination of those variants. LoadState has three variants and Event has three, so there are nine pairs. The arms above cover them like this:
(_, Fetch())covers three pairs.- The two
Loading()arms cover two more. - The last arm covers four pairs:
LoadedandFailed, each withSucceededandErrored.
Delete the last arm and compilation fails. The error names the missing case, for example The type 'LoadState<List<String>>' is not exhaustively matched by the switch cases ... '(Loaded(), Succeeded())'. The exact wording varies by SDK version, but it lists an uncovered pair.
Now add a new event:
final class Cancelled extends Event {
const Cancelled();
}Every switch over (state, event) stops compiling until you decide what Cancelled does in each state. That is the point of this design. The compiler tells you which tables to update.
Order matters, and wildcards hide gaps
Dart checks arms from top to bottom, and the first match wins. In the reducer, (_, Fetch()) comes first, so no later arm needs to mention Fetch. If you moved it to the bottom, it would still be correct. But a broader arm placed above a narrower one makes the narrower one unreachable, and the compiler warns you about it.
A narrower use of _ is fine. In (_, Fetch()) the wildcard stands for "every state", and that is the intent. Use _ when you really mean "all current and future variants" and want a new state to behave the same way. Write the variants out when a new one should force a decision.
Guards in transitions
A when clause adds a condition to an arm. This version of the reducer stops retrying after three failed attempts. The count lives outside the state, so the function takes it as a parameter.
LoadState<List<String>> reduceWithLimit(
LoadState<List<String>> state,
Event event,
int attempts,
) =>
switch ((state, event)) {
(Failed(), Fetch()) when attempts >= 3 => state,
(_, Fetch()) => const Loading(),
(Loading(), Succeeded(items: final items)) => Loaded(items),
(Loading(), Errored(error: final e)) => Failed(e),
(Loaded() || Failed(), Succeeded() || Errored()) => state,
};The compiler does not count a guarded arm toward exhaustiveness, because it cannot tell when the guard is true. That is why the unguarded (_, Fetch()) follows it. Without that arm, the Fetch pairs would be reported as missing. The guarded arm must also come first. If it came after (_, Fetch()), it would never run.
Keeping the reducer pure
A reducer should be a pure function: the same inputs always give the same output, and it touches nothing outside itself. In the guarded version, attempts is a parameter instead of a global variable, which keeps it that way. Network calls, timers and setState belong in the code that creates events and calls reduce, not in the reducer.
A common wiring in Flutter looks like this:
import 'package:flutter/foundation.dart';
class ItemsController extends ChangeNotifier {
LoadState<List<String>> _state = const Loading();
LoadState<List<String>> get state => _state;
void dispatch(Event event) {
_state = reduce(_state, event);
notifyListeners();
}
Future<void> load(Future<List<String>> Function() fetch) async {
dispatch(const Fetch());
try {
dispatch(Succeeded(await fetch()));
} catch (e) {
dispatch(Errored(e));
}
}
}The controller owns the mutable field and the side effects. reduce owns the rules. This assumes LoadState, Event and reduce are in scope, for example imported from reducer.dart.
Testing the reducer
Because reduce is a plain function, a test needs no widgets, no mocks and no async code. Add package:test to dev_dependencies. In a Flutter project, flutter_test provides the same test and expect.
import 'package:test/test.dart';
import 'reducer.dart';
void main() {
test('Fetch moves any state to Loading', () {
expect(reduce(const Failed('x'), const Fetch()), isA<Loading>());
});
test('Succeeded while Loading carries the items', () {
final next = reduce(const Loading(), const Succeeded(['a']));
expect(next, isA<Loaded<List<String>>>());
expect((next as Loaded<List<String>>).data, ['a']);
});
test('a late Errored event leaves Loaded unchanged', () {
const state = Loaded(['a']);
expect(identical(reduce(state, const Errored('late')), state), isTrue);
});
}The state classes don't override ==, so the tests check types and fields instead of comparing whole objects. The last test uses identical because the reducer returns the same instance for ignored events. If you add equality to your states, you can compare them directly.
Test the interesting pairs: the ignored ones, the guarded ones, and each arrow in the diagram. The compiler already proves that none is missing, so the tests only need to check that each one is correct.
Edge cases to remember
- Both parts of the record must be sealed. If
Eventwere an ordinary class, the compiler would demand a wildcard arm, and you would lose the check. - A sealed type can only be extended in the library where it is declared. In practice, keep
LoadStateandEventin the same file as the reducer, or in files that arepartof one library. - Generic arguments matter.
LoadState<List<String>>andLoadState<int>are different types, so a reducer written for one cannot take the other without being generic itself. - If a state needs history, such as "show the old list while refreshing", put the data in the variant (
Loadingwith apreviousfield), not in a second variable beside the state.
Exercise
Add a Cancelled event to the reducer. A cancel while Loading should return to Failed with the error 'cancelled'. In Loaded and Failed it should change nothing. Which arms do you change, and what does the compiler do if you forget the second rule?
Show answer
Add final class Cancelled extends Event { const Cancelled(); }. In reduce, add the arm (Loading(), Cancelled()) => const Failed('cancelled'). Extend the last arm to (Loaded() || Failed(), Succeeded() || Errored() || Cancelled()) => state. (_, Fetch()) needs no change. If you forget the last change, compilation fails with a non-exhaustive switch error that names (Loaded(), Cancelled()) and (Failed(), Cancelled()) as unmatched. If you had used a _ => state fallback instead, the code would compile and silently ignore Cancelled everywhere, including the case in Loading that you meant to handle.
Exercise
Why does reduceWithLimit put the guarded arm (Failed(), Fetch()) when attempts >= 3 before (_, Fetch())?
Show answer
Arms are tried from top to bottom and the first match wins. If (_, Fetch()) came first, it would match every fetch, including the one from Failed, so the guarded arm would never run. The unguarded (_, Fetch()) is still needed after it, because the compiler does not count guarded arms toward exhaustiveness.