dart-code-checker / dart-code-metrics

Software analytics tool that helps developers analyse and improve software quality.
https://dcm.dev
Other
860 stars 265 forks source link

[new rule] Handle all possible states in BlocBuilder #1244

Open enseitankad0 opened 1 year ago

enseitankad0 commented 1 year ago

Hi. I noticed that this is happening quite often when team member forgets to handle Error state coming from Bloc. Can we have special rule for it? Similar to list all props in equatable get props

builder: (BuildContext context, EvChargerState state) {

if (state is LoadingState) {
    return Text('LoadingUserState)
}

if (state is LoadedUserState) {
    return Text(state.name);
}
 // DCM error: There is one State not handled in BlocBuilder : UserErrorState.  <--- New rule needed
quoc-huynh-cosee commented 1 year ago

With Dart 3 you use the new class modifier sealed for that.

sealed class UserState {}
final class LoadingState extends UserState {}
final class LoadedUserState extends UserState {}
final class UserErrorState extends UserState {}

You can now use exhaustive switching

builder: (context, state) {
    return switch(state) {
        LoadingState() => Text('LoadingUserState),
        LoadedUserState() => Text(state.name),
        UserErrorState() => Text('Error'), 
    }
}

If you forgot one state e.g. UserErrorState you will receive an error.

The type 'UserState' 'is not ex exhaustively matched by the switch case since it doesn't match UserErrorState()