الانتقال إلى المحتوى
تطبيقات الموبايلDart· 6 دقائق للقراءة

Stop Modeling Screens with Flags: Sealed Classes and Exhaustive Switches in Dart 3

Three flags describe eight states when your screen has three. A sealed class lists the real ones, and the compiler checks you handled each.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Dart 3
محتويات المقال

The crash report says "Null check operator used on a null value", thrown from the profile screen's build on its very first frame. The Cubit started with const ProfileState(): not loading, no error, no user yet. The build method checked for loading, then for an error, and then did what the remaining branch always does: state.user!.name. Nobody wrote a branch for "nothing has happened yet", because nobody thought of it as a state.

The common misconception

The belief: one state class with isLoading, error and data fields is the simplest safe way to model a screen. It's one class with one copyWith, and every widget can read every field.

The first half is true. The Bloc library's own guide lists this approach as "Simple" and "Concise", and it's a shape most developers have written many times. It also has a real strength: states that overlap, such as showing an error snackbar while the old data stays on screen, fit naturally. The trouble is the word "safe". The same guide's first con is "Not Type Safe", and it warns that "it's possible to emit a malformed state which can lead to bugs."

What actually happens

Three fields, eight states

A bool and two nullable fields give 2 × 2 × 2 = 8 possible combinations. The screen means something by maybe three of them: loading, loaded with a user, failed with a message. The rest are still valid Dart. ProfileState(isLoading: true, error: 'Timeout', user: mona) compiles, and when we passed it to the build method below, the screen showed a spinner and silently dropped both the error and the user.

Every if is a promise the compiler can't check

With flags, the order of your if statements decides what the screen shows, and the last branch assumes everything before it has ruled out the bad cases. That's where the ! comes in: a that says "trust me, the user is here". Run that build method on the initial ProfileState() and it throws exactly the crash from the report, a TypeError with "Null check operator used on a null value".

sealed closes the family

Dart 3 added class modifiers; besides abstract, they "require a language version of at least 3.0". The one you want here is sealed: "To create a known, enumerable set of subtypes, use the sealed modifier." A can't be extended or implemented outside its own library, and it's "implicitly abstract", so you can't create a plain ProfileState. Because every direct subtype lives in the same library, "the compiler is aware of any possible direct subtypes".

The switch must cover every state

That knowledge powers , which "reports a compile-time error if it's possible for a value to enter a switch but not match any of the cases". Each case is a pattern that can also pull data out: ProfileLoaded(:final user) binds user only inside that case. The patterns docs put it this way: "The values that a pattern destructures in a case become local variables." No nullable field, no !.

Rewriting the profile state

Dart profile_state.dart
class ProfileState {  const ProfileState({this.isLoading = false, this.error, this.user});  final bool isLoading;  final String? error;  final User? user;}Widget buildProfile(ProfileState s) {  if (s.isLoading) return const CircularProgressIndicator();  if (s.error != null) return Text(s.error!);  return Text(s.user!.name); // nothing stops user from being null here}

The initial state is now ProfileLoading(), because a screen that's waiting for data is loading. To see the compiler earn its keep, we added final class ProfileOffline extends ProfileState and ran dart analyze. It reported an error, not a warning: "The type 'ProfileState' isn't exhaustively matched by the switch cases since it doesn't match the pattern 'ProfileOffline()'." Every switch that needs updating is now on a list, before the app runs.

With Bloc, these subclasses are still states that emit compares, so the ones that carry data need value equality, from == or Equatable. The Bloc FAQ's own example does exactly that: sealed class MyState extends Equatable, with each final class listing its fields in props.

Flags in one classSealed class
Impossible combinationsCompile fineCan't be built
Reading the dataNull checks and !Destructured in the matching case
Adding a new stateA new flag; old if chains don't noticeEvery non-exhaustive switch fails to compile
States that overlapNatural: keep data while showing an errorPut the shared data in each state that needs it
Amount of codeLessOne class per state

How to apply it in your project

  1. List the states the user can seeWrite them down for one screen: loading, loaded, empty, failed, offline. If two can never be on screen at once, they're separate states.
  2. Give each state only its own dataOne final class per state under a sealed base. A loaded state has a non-nullable user; a failed state has a message.
  3. Switch in build, without a wildcardUse a switch expression with one case per subtype and destructure what you need, so the build method has no !.
  4. Start from a real statePick an initial state that the switch already handles, such as ProfileLoading(), instead of an empty object.
  5. Let the compiler drive changesWhen you add a state, run the analyzer and fix every error it lists. That list is your change set.

Key takeaways

  • Each boolean or nullable field doubles the number of states your class can hold, wanted or not.
  • A flags class makes "impossible" states legal, and ! turns them into runtime crashes.
  • A Dart 3 sealed class fixes the set of subtypes, so the compiler knows every state.
  • A switch over a sealed type must be exhaustive; a missing state is a compile error.
  • Avoid _ over your own sealed states, and keep the flags model for states that truly overlap.

📚 المصادر

  1. Class modifiers: sealed — Dart docs
  2. Branches: exhaustiveness checking — Dart docs
  3. Patterns — Dart docs
  4. Modeling state — Bloc library

التعليقات (0)