Dart: switch case of a class?

Viewed 49

Hello Guys, I hope you are doing well!

I got a question, it's how to use switch case on a class? (Here the 'state' is the main class, and other classes are inherited from state.)

like for example, I tried to replace this:

if(state is LoadingPage)        {return LoadingPage;}
else if {state is SuccessPage)  {return SuccessPage;}
else if {state is FailPage)     {return FailPage;}

to this:

switch (state){
case LoadingPage:   {return LoadingPage;}
case SuccessPage:   {return SuccessPage;}
case FailPage:      {return FailPage;}
}

It didn't work, what worked for me is making the state as a string, like this:

switch (state.toString()){
    case 'LoadingPage':      {return LoadingPage;}
    case 'SuccessPage':      {return SuccessPage;}
    case 'FailPage':         {return FailPage;}
    }

It works though, but it's a short time solution, like if I had to edit something, it gonna be so hard to change everything (since it's a string)..

1 Answers

There is a package named freezed for this exact solution where we do not use switch rather map and/or maybeMap.

@freezed
class MemberState with _$MemberState {
  factory MemberState.initial() = _MemberStateInitial;
  factory MemberState.loading() = _MemberStateLoading;
  factory MemberState.loadSuccess({required MemberDetail detail}) =
      _MemberStateLoadSuccess;
  factory MemberState.loadFailure({required AppFailure failure}) =
      _MemberStateLoadFailure;
}

Usage:

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<MemberBloc, MemberState>(
      builder: (context, state) {
        return const Scaffold(
          body: state.map(
              initial: initial,
              loading: loading,
              loadSuccess: loadSuccess,
              loadFailure: loadFailure),
        );
      },
    );
  }

Of course, I use it with BLoCs but the underlying concept is the same. You can use it in any way you like. And, the best thing is it is all generated automatically. So, you wouldn't have to write the code yourself.

Related