Sub topic 2
Sealed classes: a closed set of subtypes
This chapter assumes you know Dart classes, constructors, final fields, null safety and basic generics. It also assumes Dart 3 or later. The previous chapter showed how flags and nullable fields allow impossible states. Here you learn the language feature that fixes this: the sealed modifier.
What `sealed` means
A sealed class is a class whose direct subtypes are all known to the compiler. Dart enforces this with one rule: a sealed class can only be extended or implemented inside the library where it is declared. A library is usually a single .dart file. Files joined with part and part of count as one library.
Code in other files can use a sealed type, pass it around and check it. It cannot add a new subtype. Because the full list of subtypes is fixed, the compiler can later check that you handled every one of them.
A sealed class is also implicitly abstract. You cannot write LoadState() to create an instance. Only its subtypes can be instantiated. You never need to write abstract yourself. Adding it is allowed but redundant.
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() {
LoadState<int> state = const Loading();
print(state is Loading<int>);
state = const Loaded(42);
print(state is Loaded<int>);
// LoadState<int>(); // Compile-time error: abstract classes can't be instantiated.
}The parent class has a const constructor. A subclass constructor must call a superclass constructor, so the sealed class needs a generative constructor even though nobody calls it directly. Making it const lets the subclasses be const too, which allows const Loading() and cheaper widget rebuilds.
The hierarchy as a picture
Each subclass is one valid state. Each carries only the fields that make sense for it. Loading has none, Loaded has data, and Failed has error.
Compare this with a class holding bool isLoading, List<String>? items and Object? error. That class can express "loading and failed at the same time" or "loaded, but items is null". The sealed hierarchy cannot. A Loaded always has data, and a Failed always has an error.
The same-library rule
The restriction applies to the sealed class itself. Suppose load_state.dart declares LoadState. In any other file, both of these fail to compile:
// another_file.dart (does not compile)
import 'load_state.dart';
final class Cancelled<T> extends LoadState<T> {} // error: can't extend a sealed class outside its library
final class Paused<T> implements LoadState<T> {} // error: can't implement it eitherThis is deliberate. If any file could add Cancelled, a switch in another package could no longer be checked for completeness. The restriction is what makes exhaustiveness checking possible.
The rule has a practical consequence. Put the sealed class and all its subtypes in the same file. Keep that file small and focused on one feature's state.
What a sealed class can contain
Because a sealed class is abstract, it can hold everything an abstract class can:
- Fields and constructors that subclasses call.
- Concrete methods and getters shared by every state.
- Abstract members that each subclass must implement.
- Factory constructors that return one of the subclasses.
A factory constructor is a convenient way to give callers a single entry point:
sealed class Result<T> {
const Result();
factory Result.ok(T value) = Ok<T>;
factory Result.error(Object error) = Err<T>;
bool get isOk => this is Ok<T>;
}
final class Ok<T> extends Result<T> {
const Ok(this.value);
final T value;
}
final class Err<T> extends Result<T> {
const Err(this.error);
final Object error;
}
void main() {
final Result<String> a = Result.ok('saved');
final Result<String> b = Result.error('disk full');
print(a.isOk);
print(b.isOk);
}The redirecting factories = Ok<T> and = Err<T> work because the subclasses are in the same library. Keep shared members small. Logic that differs per state belongs in a switch, which later chapters cover.
Modifiers on the subtypes
Subtypes of a sealed class may use any class modifier. The choice controls what code outside the library can do with them:
| Modifier on the subtype | Can code outside the library extend it? | Typical use |
|---|---|---|
| `final class` | No (no extending, no implementing) | Leaf states, the default choice |
| `class` (no modifier) | Yes | Rare, since it reopens the hierarchy below that point |
| `base class` | Extend only, and subclasses must be `base`, `final` or `sealed` | When subclasses must inherit your constructor logic |
| `sealed class` | No, and it creates a nested closed group | Grouping related states (see below) |
| `interface class` | Implement only | Rare for state types |
This chapter's examples use final for every leaf. A leaf marked final cannot be subtyped anywhere, so nothing can slip in below it. The topic's code examples follow the same pattern.
Nested sealed groups
A subtype can itself be sealed. The compiler then knows the full tree. This is useful when states fall into families:
sealed class Upload {
const Upload();
}
sealed class InProgress extends Upload {
const InProgress();
}
final class Queued extends InProgress {
const Queued();
}
final class Sending extends InProgress {
const Sending(this.percent);
final int percent;
}
final class Done extends Upload {
const Done(this.url);
final String url;
}
String label(Upload u) => switch (u) {
Queued() => 'Waiting',
Sending(percent: final p) => 'Sending $p%',
Done(url: final url) => 'Done: $url',
};
void main() {
print(label(const Sending(40)));
print(label(const Done('https://example.com/a.png')));
}The switch lists the leaf states. It could also have a single InProgress() case that covers both Queued and Sending. Do not nest groups unless the grouping helps your code, because each extra level makes the model harder to read.
What the compiler gains
Declaring the class sealed has one practical payoff, which the later chapters on switch expressions and exhaustiveness use fully. Take a switch over a LoadState. If you list Loading() and Loaded() but forget Failed(), the compiler reports a non-exhaustive switch and names the missing type. If you later add a fourth subclass, every switch over LoadState in the project fails to compile until you handle it.
This turns a runtime surprise into a list of compile errors. With an ordinary abstract class, the compiler would accept the incomplete switch, and the missing case would show up as a bug.
Sealed versus the alternatives
| Feature | Fixed set of cases | Cases carry different data | Compiler checks `switch` is complete |
|---|---|---|---|
| `enum` | Yes | Limited (same fields for every value) | Yes |
| `abstract class` | No, anyone can subclass | Yes | No |
| `sealed class` | Yes, within one library | Yes | Yes |
An enum is enough when the cases are only labels, such as Direction.north. A sealed class fits when different cases need different fields. A later chapter compares sealed classes with code-generated unions.
Common mistakes
- Putting subclasses in a different file from the sealed class. The compiler rejects them. Move them into the same library, or use
partfiles. - Writing
abstract sealed class. It compiles, butabstractadds nothing. - Forgetting
constconstructors and then wondering whyconst Loading()is rejected. - Leaving a leaf subclass as a plain
class. Code elsewhere can then extend it, so aswitchstill compiles but the subclass may carry state you did not plan for. Preferfinal. - Using a sealed class for an open-ended set, such as plugin types. If third parties must add cases, use an ordinary abstract class or an interface.
Exercises
Exercise
A teammate writes final x = LoadState<int>(); and gets a compile error, even though LoadState has a constructor. Why, and what should they write instead?
Show answer
A sealed class is implicitly abstract, so it cannot be instantiated. They should create one of its subtypes, for example const Loading<int>() or Loaded(42), and assign it to a variable of type LoadState<int>.
Exercise
You declare sealed class Auth in auth.dart, with LoggedOut and LoggedIn in the same file. A colleague adds final class Guest extends Auth {} in guest.dart. What happens, and why does Dart work this way?
Show answer
Compilation fails, because a sealed class can only be extended inside its own library. The restriction guarantees that the compiler knows every subtype of Auth, which is what lets it check that a switch over Auth covers all cases. The fix is to move Guest into auth.dart, or into a part file of it.