Home > Enterprise >  Flutter Bloc - is there a way to provide different instances of a bloc in a screen
Flutter Bloc - is there a way to provide different instances of a bloc in a screen

Time:10-28

I have a cubit named FoodCubit which has two functions:

-getAllFoods()

-getFilteredFoods(category)

And I have a screen like below HomeScreen

As you can see top part of the screen is a blocbuilder returning states emitted by my first function which is called in didChangeDependency() And the bottom part is another blocbuilder of the same FoodCubit which I want to return states emitted by second function But the results in top blocbuilder and bottom blocbuilder are the same. I used a blocprovider in parent of my material app providing FoodCubit. I was wandering if there is a way to provide two instances of same bloc and use it. Some how like

MultiBlocProvider(
Providers:[
//first bloc provider
BlocProvider(), 
//second bloc provider
BlocProvider() 
)

But then how can I reach it in blocbuilder??

I think one work around is to use two blocproviders for top and bottom part of screen but wouldn't that just destroy purpose of using blocs. Is there any way around it? Is there a better way?

CodePudding user response:

There are several options you can try here:

  1. Create a subclass of the bloc:
class FirstBloc extends FoodCubit {}
class SecondBloc extends FoodCubit {}
  1. Create mixins of the bloc:
mixin FirstBloc on Bloc {}

mixin SecondBloc on Bloc {}

class FoodCubit extends Bloc with FirstBloc, SecondBloc {
  getAllFoods()

  getFilteredFoods(category)
}
// Then in your widget
... 
BlocProvider<FirstBloc>(
     create: (_) => FoodCubit(),
     child:
...
BlocProvider<SecondBloc>(
     create: (_) => FoodCubit(),
     child:
...

CodePudding user response:

You could just emit the same state for both events, that has a "all" list and a "filtered" list.

You would not need two BlocBuilders either, it could be just one.

  • Related