
Stop Modeling Screens with Flags: Sealed Classes and Exhaustive Switches in Dart 3
- كاتب موثّق
- Dart 3
محتويات المقال
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
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.
What actually happens
Three fields, eight states
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
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
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
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
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}sealed class ProfileState { const ProfileState();}final class ProfileLoading extends ProfileState { const ProfileLoading();}final class ProfileLoaded extends ProfileState { const ProfileLoaded(this.user); final User user;}final class ProfileFailed extends ProfileState { const ProfileFailed(this.message); final String message;}Widget buildProfile(ProfileState s) => switch (s) { ProfileLoading() => const CircularProgressIndicator(), ProfileLoaded(:final user) => Text(user.name), ProfileFailed(:final message) => Text(message), };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.
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.
! | ||
if chains don't notice | ||
How to apply it in your project
List the states the user can see Write them down for one screen: loading, loaded, empty, failed, offline. If two can never be on screen at once, they're separate states. Give each state only its own data One final classper state under asealedbase. A loaded state has a non-nullable user; a failed state has a message.Switch in build, without a wildcard Use a switch expression with one case per subtype and destructure what you need, so the build method has no !.Start from a real state Pick an initial state that the switch already handles, such as ProfileLoading(), instead of an empty object.Let the compiler drive changes When 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 sealedclass 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.
التعليقات (0)