Sub topic 1
Why flags and nullable fields allow impossible states
Prerequisites
This chapter assumes you know Dart classes, constructors, final fields, and null safety. You need Dart 3 or later installed to run the code.
The problem with flags and nullable fields
A screen that loads a list often tracks its state with several variables:
class ItemsState {
bool isLoading = false;
List<String>? items;
Object? error;
}Each boolean has two values, and each nullable field has two states (set or null). Together these allow 2 × 2 × 2 = 8 combinations. The screen has only three meaningful states: loading, loaded, and failed. The other five combinations are impossible, yet the compiler accepts them. An object can be loading and failed at once, or hold items and an error together. Every method that reads this object must guess which combination it received.
Sealed classes: a closed set of subtypes
A sealed class is a class that only subclasses in the same library can extend. A library is one Dart file and any part files it includes. Because the compiler knows every subtype, it can check that code handles all of them.
Writing one subclass per state
Give each valid state its own subclass. Each subclass holds only the data that state needs:
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;
}A Loading value has no data field, so you cannot read items from it. The impossible combinations no longer exist in the type.
Switch expressions over a sealed type
A switch expression picks a result based on the variant. Destructuring pulls the fields out in the same step:
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
Failed(error: final e) => 'Error: $e',
};The compiler checks that every subtype has an arm. If you add a fourth state and do not update this function, the code fails to compile.
> Note: Dart reports a compile error for a missing arm, so you find gaps before running the app.
Exercise
If you remove the Failed arm from describe, what happens?
Show answer
The code fails to compile with a non-exhaustive switch error, because LoadState has a Failed subtype that the switch does not handle.