Sub topic 3
Writing one subclass per state
Assume you know Dart classes, constructors, final fields, null safety, basic generics, and Flutter’s build method. You also need Dart 3 or later because sealed classes and pattern matching are Dart 3 features.
A screen often has states such as:
- The app is loading data.
- The app loaded data successfully.
- The app failed to load data.
A single class with flags and nullable fields can represent invalid combinations. For example, isLoading might be true while error also contains an error. Separate subclasses make each valid state explicit.
Create a sealed base class
A sealed class is a base class with a closed set of direct subtypes. The compiler knows which classes belong to that set. Each subtype is called a variant.
Start with a generic base class:
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>> first = Loading();
const LoadState<List<String>> second = Loaded(['Dart', 'Flutter']);
final LoadState<List<String>> third = Failed(StateError('Network error'));
print(first);
print(second);
print(third);
}LoadState<T> is the common type. The type parameter T describes the successful result. A LoadState<List<String>> can therefore contain a list when loading succeeds.
Each subclass carries only the data that makes sense for that state:
Loadingcarries no result or error.Loadedcarriesdata.Failedcarrieserror.
The const constructors allow immutable, compile-time instances where their values are constant. The final fields cannot be reassigned after construction.
Choose class modifiers deliberately
The sealed modifier closes the direct subtype set. The final modifier on each variant prevents another class from extending that variant.
Use final class when a state is a concrete case. Use base, interface, or final only when you deliberately need different inheritance behavior.
A subclass can also contain methods when that behavior belongs to the state itself, but simple data classes are usually easier to inspect and test. Keep operations such as fetching data in a repository or controller rather than inside Loading.
Visualise the hierarchy
The hierarchy separates the identity of a state from its payload. Later, a switch expression can inspect that identity and read the matching payload without guessing which fields are available.
Exercise
Design a sealed AuthState hierarchy with SignedOut, SigningIn, and SignedIn. Which data should SignedIn carry?
Show answer
SignedIn should carry the authenticated user, such as User user. SignedOut and SigningIn need no user field.