Bloc: switch-case for state distinction? Use state.runtimeType?

Created on 10 Aug 2020  路  2Comments  路  Source: felangel/bloc

I learned to distinct between the different bloc states by using "if-else" and "is"

BlocBuilder<MyBlocEvent, MyBlocState>(
      builder: (context, state) {
            if(state is MyBlocState) {
                  return WidgetA();
            }
            else if(state is MyOtherBlocState) {
                  return OtherWidget();
            }
            else {
                  return Container(); 
            }
      ),

I feel like this is a situation where a switch-case statement would be better suited, however switch-case in dart does not support class-comparison.

I tried using a switch-case on state.runtimeType and it actually works fine:

BlocBuilder<MyBlocEvent, MyBlocState>(
      builder: (context, state) {
            switch (state.runtimeType) {
                  case MyBlocState:
                        return WidgetA();
                  case MyOtherBlocState:
                        return WidgetA();
                  default:
                        return Container();
                  }
            }
      ),

Can you think of any reasons why I should not implement it like this? Any hidden dangers?

I'm curious for your answers.

question

Most helpful comment

Hey @felangel ,

thanks for your quick reply.
That totally makes sense and I will stick to if-else then.
Best regards 鉁岋笍

All 2 comments

Hi @Tiebo 馃憢
Thanks for opening an issue!

runtimeType isn't something you should use for program logic. It changes based on compiler options and actually using it can make optimizations for your app much harder. Also it doesn't work properly with subclasses and generics which is why is exists.

Hope that helps 馃憤

Hey @felangel ,

thanks for your quick reply.
That totally makes sense and I will stick to if-else then.
Best regards 鉁岋笍

Was this page helpful?
0 / 5 - 0 ratings