Sub topic 2
Sealed classes: a closed set of subtypes
Assume you know Dart classes, constructors, final fields, null safety, basic generics, Flutter widgets, and the build method. You also need Dart 3 or later because sealed classes and pattern matching were introduced in Dart 3.
A screen often has a small number of valid states. For example, an item list can be loading, loaded, or failed. A common first design uses flags and nullable fields:
bool isLoading = false;
List<String>? items;
Object? error;This design allows invalid combinations. The screen can be loading while also showing an error. It can contain both items and an error. It can have no items, no error, and isLoading == false, even though the program does not know what that means.
A sealed class models the valid alternatives directly. A sealed class is a class whose direct subtypes are known at compile time. Each subtype represents one state.
Declare a sealed state hierarchy
Start with an abstract-looking base type:
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;
}
void main() {
const LoadState<List<String>> state = Loaded(['Ada', 'Lin']);
print(state);
}LoadState<T> is the common type. The type parameter T describes the data produced by a successful load. For a list screen, T can be List<String>. For a profile screen, it could be User.
Each subtype stores only the data that belongs to that state:
Loadingneeds no result data.Loadedrequires a result.Failedrequires an error.
The constructors are const, so instances can be compile-time constants when their values are constant. The subclasses are final, which prevents further subclassing. This gives the hierarchy a clear and controlled shape.
What “closed” means
A sealed class is closed to extensions outside its library. Dart can therefore know the complete set of direct subtypes. That information enables exhaustive pattern matching, which you will use to handle every state without a default branch.
The subclasses must be declared in the same Dart library as the sealed class. In a typical application, keeping the base class and its state variants in one file is the simplest arrangement.
A sealed class does not automatically enforce business rules inside a state. For example, Loaded<List<String>> can still contain an empty list. That is a valid loaded state, but the UI may want to display it differently. The type hierarchy describes the main alternatives; patterns and guards refine those alternatives later.
Exercise
What invalid combinations does a sealed LoadState hierarchy prevent compared with separate loading, data, and error fields?
Show answer
It prevents combinations such as loading and failed at the same time, because one LoadState value is one specific variant: Loading, Loaded, or Failed.