I've started using Bloc in my project. I've one confusion that I want to clear. Suppose I have got the following cubits:
--- Auth Cubit
--- Category Cubit
--- Cart Cubit
--- Orders Cubit
Now, in order to add them to the project I've two options. Either I use MultiBlocProvider
and initialized all of them in the main.dart
app or I use scopped approach. In the case of scopped approach, flutter will initialize it over and over.
From my understanding, if I initialize providers globally I will be able to remove or update them easily. However, in scopped case, I've to change it in multiple classes.
I want to know which approach is best performance-wise and what could be the pros and cons of both approaches.
CodePudding user response:
I haven‘t measured the performance of my approach, but my approach is the following:
Bloc‘s that use the same data multiple times in a session, I instantiate in main or app. This would be auth. and cart, maybe category.
Bloc‘s that always run with a new set of data, I instantiate on occasion such as editing an entry of a list of things. This might be Order in your case, if this is the process of checking-out
CodePudding user response:
According to flutter_bloc:
By default,
BlocProvider
will create the bloclazily
, meaning create will get executed when the bloc is looked up via BlocProvider.of(context).
Hence it is better to use MultiBlocProvider
and initialize all the Cubits at the start of the app. Performance in taken care by the BlocProvider
BlocProvider
should be used to create newblocs
which will be made available to the rest of the subtree. In this case, sinceBlocProvider
is responsible for creating the bloc, it will automatically handle closing it.
MultiBlocProvider(
providers: [
BlocProvider<BlocA>(
create: (BuildContext context) => BlocA(),
),
BlocProvider<BlocB>(
create: (BuildContext context) => BlocB(),
),
BlocProvider<BlocC>(
create: (BuildContext context) => BlocC(),
),
],
child: ChildA(),
)