felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.79k stars 3.39k forks source link

switch-case for state distinction? Use state.runtimeType? #1595

Closed tmaihoff closed 4 years ago

tmaihoff commented 4 years ago

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.

felangel commented 4 years ago

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 👍

tmaihoff commented 4 years ago

Hey @felangel ,

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

talksik commented 1 year ago

what's the recommended approach with pattern matching now in dart? I am confused whether I should use freezed or some other pattern so that I can get the x.when(...)

Anyone familiar with this pattern? Thanks

OnlyTarg commented 1 year ago

@talksik With new dart you can use switch statement https://github.com/felangel/bloc/blob/master/examples/flutter_bloc_with_stream/lib/main.dart