Sub topic 3
Writing one subclass per state
This chapter assumes you know Dart classes, constructors, final fields, null safety, and basic generics. It also assumes you have seen the idea of a sealed class, which the previous chapter introduced. Here the focus is on the next step: turning each valid state of a feature into its own subclass, and deciding what data each subclass carries.
The rule: one subclass per state
A sealed class lists a closed set of subtypes. To use it for state, write one subclass for each distinct state a feature can be in. Each subclass holds only the data that is meaningful in that state.
Take a screen that loads a list of items. It has three states:
- Loading: a request is in flight. There is no data and no error.
- Loaded: the request succeeded. There is data and no error.
- Failed: the request failed. There is an error and no data.
Here is the hierarchy:
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;
}Compare this with a single class that has bool isLoading, List<String>? data, and Object? error. That class can represent "loading with an error" or "loaded with no data and no error". Those combinations are meaningless, but the type allows them. In the hierarchy above, a Loaded value cannot have an error because the field does not exist on that type. The compiler removes the impossible states for you.
Reading the declaration piece by piece
The sealed base class
sealed class LoadState<T> is abstract. You cannot write LoadState() to create an instance. Only the subclasses can be instantiated. The base class also tells the compiler that the full list of direct subtypes is known, which is what later enables exhaustive checking.
The const LoadState(); constructor lets subclasses have const constructors. Without it, a const subclass constructor would be a compile error, because a const constructor needs a const superclass constructor.
The `final class` modifier
Each variant is declared final class. A final class cannot be extended, implemented, or mixed in outside its own library. Without it, another library could not subclass Loaded anyway if it were in the same library as the sealed class, but within that library you or a teammate could add class Refreshing extends Loaded<T>. That would create a hidden sub-variant, and a switch that matches Loaded() would silently cover it.
Using final on the leaf classes keeps the hierarchy exactly one level deep. The set of states is the set of leaf classes, and nothing else hides underneath.
If you do want a deeper tree, you can make a variant sealed itself. Exhaustiveness then flows through both levels. That is a deliberate design choice, not a default.
Constructors and `const`
Each variant has a const constructor. The Loading state has no fields, so const Loading() always produces a compile-time constant. Dart canonicalizes const instances, so const Loading<String>() == const Loading<String>() is true because they are the same object. That makes Loading cheap to create and compare.
Loaded and Failed have a positional parameter each. You could use named parameters (Loaded({required this.data})) if you prefer. Positional works well for a single field, and the object pattern syntax you will see in the next chapters uses the field name anyway, not the position.
Choosing what each variant carries
The main design question is what goes into each subclass. A useful test: for every field, ask "is this value always present and meaningful in this state?" If yes, make it a non-nullable final field on that subclass. If it is only sometimes present, you probably have two states folded into one.
A common case is a screen that keeps showing old data while it refreshes. You could add a nullable previous field to Loading, but a clearer option is to add a variant:
final class Refreshing<T> extends LoadState<T> {
const Refreshing(this.stale);
final T stale;
}Refreshing always has stale data. Loading never does. Neither field is nullable.
Fields that belong to every state
Sometimes all states share a value, such as a request ID or a timestamp. Put it on the sealed base class as a field or abstract getter:
sealed class Job {
const Job(this.id);
final String id;
}
final class Queued extends Job {
const Queued(super.id);
}
final class Running extends Job {
const Running(super.id, this.startedAt);
final DateTime startedAt;
}
final class Done extends Job {
const Done(super.id, this.result);
final String result;
}Every Job has an id, so code that does not care about the state can read job.id without a switch. Only Running has startedAt, and only Done has result.
Keep shared fields rare. If you find the base class growing nullable fields to serve some variants, move them down into the subclasses.
Generics on the hierarchy
LoadState<T> is generic so you can reuse it for lists, single objects, or any other payload. Each subclass repeats the type parameter and passes it up: extends LoadState<T>.
Two details matter here:
Loading<T>andFailed<T>do not useTin any field. They still declare it so that aLoading<String>is aLoadState<String>. Without the parameter, they could only extendLoadState<dynamic>or a fixed type.- Type inference may not know
Twhen you writeconst Loading(). If you assign it to a variable of typeLoadState<List<String>>, Dart infersTfrom the context. If you writefinal s = const Loading();with no context,Tbecomesdynamic, which is rarely what you want. Annotate the variable or writeconst Loading<List<String>>().
const LoadState<List<String>> initial = Loading();Here the declared type supplies T.
Building values
Creating a state is just calling a constructor. Code that produces states, such as a repository wrapper or a controller, returns the right variant:
Future<LoadState<List<String>>> fetchItems(
Future<List<String>> Function() request,
) async {
try {
return Loaded(await request());
} catch (e) {
return Failed(e);
}
}Here Loaded(await request()) infers T as List<String> from the return type. Notice that no code path can produce a state that is both loaded and failed. The structure of the types forbids it.
Common mistakes
- Adding a nullable field to a variant "just in case". This brings back the problem the hierarchy was meant to solve. Add a new variant instead.
- Forgetting
conston constructors for stateless variants likeLoading. It still works, but you lose canonicalization and pay for new allocations on each rebuild. - Leaving out the type parameter on a variant, as in
final class Loading extends LoadState<dynamic>. ALoadingis then never aLoadState<String>, and assignments fail with a type error. - Using
classinstead offinal classon leaves and later subclassing one. The hierarchy gets deeper without anyone deciding it should.
A diagram of the hierarchy
Summary of the design rules
| Question | Guidance |
|---|---|
| How many subclasses? | One per distinct state of the feature. |
| What fields go on a subclass? | Only non-nullable values that always exist in that state. |
| Where do shared values go? | On the sealed base class, sparingly. |
| Which class modifier for leaves? | `final class`, so the tree stays one level deep. |
| What about the type parameter? | Declare it on every variant and pass it to the base. |
Exercise
A download feature has these states: idle, downloading with a progress value from 0.0 to 1.0, finished with a file path, and failed with an error message. Write a sealed class hierarchy for it. Which variants carry data, and why is a nullable progress field on a single class a worse design?
Show answer
sealed class Download { const Download(); } final class Idle extends Download { const Idle(); } final class Downloading extends Download { const Downloading(this.progress); final double progress; } final class Finished extends Download { const Finished(this.path); final String path; } final class Failed extends Download { const Failed(this.message); final String message; } Downloading, Finished, and Failed carry data. Idle carries none. With one class and a nullable progress field, you could build a Finished-looking value that still has a progress, or an Idle value with a path. Code reading the fields would have to check for null and guess which combinations are real. In the hierarchy, progress exists only on Downloading, so it is never null and never out of place.
Exercise
You write final s = const Loading(); and then try to assign s to a variable of type LoadState<int>. What goes wrong, and how do you fix it?
Show answer
With no context, Dart infers the type argument as dynamic, so s is a Loading<dynamic>. Depending on the assignment, this may compile through dynamic but hides type errors, and it is not the type you meant. Fix it by giving the type from context, such as const LoadState<int> s = Loading();, or by writing const Loading<int>().