Sub topic 12
Same-library rule and wildcard pitfalls
This chapter assumes you can write a sealed class hierarchy and a switch expression with object patterns (covered earlier in this tutorial), and that you use Dart 3 or later. It covers two things that decide whether the compiler's exhaustiveness checking protects you. The first is the rule that limits where a sealed class can be extended. The second is the set of wildcard habits that quietly switch exhaustiveness off.
What the same-library rule says
A sealed class can only be extended, implemented, or mixed in inside the library where it is declared. In Dart, a library is normally one .dart file. Files joined with part and part of count as one library.
This rule is what makes exhaustiveness checking possible. The compiler can list every direct subtype of a sealed class because no code elsewhere can add a new one. A sealed class is also implicitly abstract, so you cannot instantiate it directly.
// lib/state/load_state.dart
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;
}Now try to add a variant from another file:
// lib/features/cancel.dart
import '../state/load_state.dart';
// Compile-time error: the class 'LoadState' can't be extended
// outside of its library because it's a sealed class.
final class Cancelled<T> extends LoadState<T> {
const Cancelled();
}Other files can still do everything except subclass:
- They can import the type.
- They can construct the concrete variants.
- They can pass values around.
- They can match on them in
switchexpressions,if-casestatements, and patterns.
Only the declaring library can grow the set of variants.
Modifiers on the subtypes
The subtypes also need thought. A direct subtype of a sealed class can be declared with final, base, sealed, or no modifier. This chapter uses final for leaf states, for two reasons:
- A
finalsubtype cannot be extended or implemented outside its library. Without the modifier, another library could subclassLoaded, and the "closed set" would then have an open door one level down. - The leaf variants stay precise, so each
Loaded()pattern matches exactly one known shape.
If a variant has its own sub-variants, make it sealed as well. The compiler expands nested sealed types recursively when it checks a switch:
sealed class Failure {
const Failure();
}
final class NetworkFailure extends Failure {
const NetworkFailure(this.statusCode);
final int statusCode;
}
final class ParseFailure extends Failure {
const ParseFailure(this.message);
final String message;
}
String explain(Failure failure) => switch (failure) {
NetworkFailure(statusCode: final code) => 'HTTP $code',
ParseFailure(message: final m) => 'Bad data: $m',
};Part files
If one file grows too large, you can split it without breaking the rule:
// lib/state/load_state.dart
part 'load_state_variants.dart';
sealed class LoadState<T> {
const LoadState();
}// lib/state/load_state_variants.dart
part of 'load_state.dart';
final class Loading<T> extends LoadState<T> {
const Loading();
}Both files form one library, so Loading may extend LoadState. Most projects keep the whole hierarchy in one file, because the file then shows every state at a glance.
Consequences for package design
The rule shapes how you publish state types.
- Inside your app, the rule is mostly a convenience. You add a variant in one file, and the compiler lists every switch that must change.
- In a package you publish, adding a variant to a public sealed class is a breaking change for consumers. Their exhaustive switches stop compiling. Plan for this by treating the variant list as part of your public API and bumping the major version when it changes.
- If you want outside code to add variants,
sealedis the wrong tool. Use anabstract interface classor a plain abstract class, and accept that no exhaustiveness checking is possible.
How a wildcard defeats exhaustiveness
A wildcard pattern _ matches anything. A switch that ends in _ is always exhaustive, whatever the subject's type. The compiler therefore stops checking whether you handled each variant. Suppose the state hierarchy gains a fourth variant, and one switch uses a wildcard:
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;
}
final class Refreshing<T> extends LoadState<T> {
const Refreshing(this.previous);
final T previous;
}
String label(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
_ => 'Something else',
};
void main() {
print(label(const Failed<List<String>>('timeout')));
print(label(Refreshing<List<String>>(['a', 'b'])));
}This prints Something else twice. It compiles with no error and no warning. A user who triggers a refresh sees "Something else" instead of their list. The compiler cannot help, because you told it you wanted a catch-all.
Remove the wildcard and the compiler reports every missing variant:
String label(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
Failed(error: final e) => 'Error: $e',
Refreshing(previous: final items) => 'Refreshing ${items.length} items',
};If you delete the Refreshing line again, you get an error like "The type 'LoadState<List<String>>' is not exhaustively matched by the switch cases since it doesn't match 'Refreshing()'".
Catch-alls that do not look like wildcards
A plain variable or typed pattern can also act as a catch-all:
String label(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
final other => 'Unhandled: $other',
};final other matches every remaining value, so the switch is exhaustive. The same applies to a type test such as LoadState() => ... on the sealed supertype itself. Both forms behave like _.
Other cases that look like they cover a variant but do not:
- Guarded cases. The compiler assumes a
whenclause can be false, so a guarded case never counts toward exhaustiveness. The following switch fails to compile, becauseLoadedwith an empty list is covered but non-empty lists are not:
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) when items.isEmpty => 'Nothing here yet',
Failed(error: final e) => 'Error: $e',
};Add an unguarded Loaded(data: final items) case after the guarded one to fix it.
- Nullable subjects. If the subject type is
LoadState<List<String>>?, you must handlenullwith anullcase or_. Prefer anullcase so that the variants stay checked. - Case order. The first matching case wins. A broad case placed before a narrow one makes the narrow one unreachable, and the analyzer reports it. Put guarded and specific cases first.
When a catch-all is the right choice
Sometimes you really mean "everything else". A common example is an if-case that cares about one variant, or a switch where several states share one result. Prefer naming the grouped variants with ||, which keeps the check intact:
bool get isBusy => switch (this) {
Loading() || Refreshing() => true,
Loaded() || Failed() => false,
};The || form lists every variant, so a new variant still produces a compile error here. Use a real wildcard only when you accept that future variants will take the default path, and consider a comment saying so.
The same care applies to the (state, event) records from the transitions chapter. A trailing (_, _) => state swallows every combination you forgot. Writing out (Loaded() || Failed(), Succeeded() || Errored()) => state is longer, but it makes the compiler check each pair.
Quick reference
| Situation | Result | Column | Column |
|---|---|---|---|
| Extend a sealed class in another file | Compile error | ||
| Match on a sealed class in another file | Allowed | ||
| Split a sealed hierarchy across `part` files | Allowed, one library | ||
| Last case is `_` or `default` | Always exhaustive, no variant checking | ||
| Last case is a guarded `when` pattern | Not counted as exhaustive | ||
| Group variants with `A() \ | \ | B()` | Exhaustive and still checked |
| Add a variant to a published sealed class | Breaking change for consumers |
Exercise
A teammate adds a Refreshing variant to your LoadState hierarchy. Your app compiles with no errors, but one screen shows the wrong text during a refresh. What most likely caused this, and how do you fix it so the same mistake is caught next time?
Show answer
That screen's switch has a wildcard (_), a default, or a catch-all variable pattern such as final other, which makes the switch exhaustive without naming Refreshing. The new variant falls into the catch-all. Remove the catch-all and list every variant, or group variants with ||. After that, any variant that is not handled produces a compile error.
Exercise
Why does this switch fail to compile, and what is the smallest change that fixes it? switch (state) { Loading() => 'a', Loaded(data: final d) when d.isNotEmpty => 'b', Failed() => 'c' }
Show answer
The Loaded case has a when guard, and the compiler assumes a guard can be false, so Loaded is not fully covered. Add an unguarded Loaded() => ... case after the guarded one.