Home > Back-end >  Flutter BLoC variables best practice
Flutter BLoC variables best practice

Time:10-08

Started recently using the BLoC approach for building apps, and one thing that is not clear is where to "keep" BLoC variables. I guess we can have these two options:

  1. Declare a variable in the BLoC class; for example in my class I can do the following:
class ModulesBloc extends Bloc<ModulesEvent, ModulesState> {
   late String myString;
}

And access it in my UI as follows:

BlocProvider.of<ModulesBloc>(context).myString;
  1. Keep it as a state variable; for example I can declare my state class as follows:
class ModulesState extends Equatable {
   const ModulesState({required this.myString});

   final String myString;

  @override
  List<Object> get props => [myString];
}

And access it in my UI as follows:

BlocBuilder<ModulesBloc, ModulesState>(
   builder: (BuildContext context, ModulesState modulesState) {
      modulesState.myString;
   }
)

Are there any performance penalties / state stability issues with any of the above approaches?

Thanks!

CodePudding user response:

I am not sure there is an absolute answer but I can at least give my opinion.

In bloc you have 3 objects: bloc, event, state.

The state is the mutable part while the bloc is a description of the your problem (what states to emit for each event). As such, an immutable variable to describe your problem should be, in my opinion, placed inside the bloc. However, anything which might change is the state of your bloc (same as the state of your widget) and should as such be stored in the state.

Example:

You want to create an app where you can set timers. In this app you can have multiple timers, each of which will be identified by a name.

In this case:

  • your state will be an object containing a double variable called timeCount, which will be incremented each seconds for example.
  • You bloc will have a final field called name which will have to be set during the creation of the stopwatch.

Interestingly enough, if you want the bloc to also handle the stopwatch creation, you will have 2 states: the first empty, the second with a name and timeCount. See how naturally name became variable and is therefore found in the state now.

  • Related