I am using Bloc for my application, however I was doing something wrong and that is, providing all BlocProvider creates in the MaterialApp
and I would not like to follow that bad practice.
Let’s suppose that when I navigate to ScreenA, we create the Bloc as follows :
case PageNames.screenA:
return PageTransition( // Some class that navigates
duration: const Duration(milliseconds: 400),
child: BlocProvider<ScreenABloc>(
create: (context) => ScreenABloc(),
child: const ScreenAPage(),
),
);
Now inside ScreenA, I will do a navigation to ScreenB, and everything is fine, however inside ScreenB at the bottom of my widget tree I want to access the ScreenABloc again, but I can’t assign a BlocProvider.value
because I get :
ProviderNotFoundException (Error: Could not find the correct Provider<ScreenABloc> above this Welcome Widget
return BlocProvider.value(
value: BlocProvider.of<ScreenABloc>(context),
child: child ...
);
So I am not sure how to get the supplier that has already been created, or if I should re-create it or what to do in those cases.
3
Answers
You can create a method of creating
BlocProvider
in the screen itself, then you can use that method for navigating and creating providers for you.Here’s an example:
you should use
BlocProvider.value
when you push a new route:then use it in both
ScreenA
andScreenB
Using all
BlocProviders
in the starting of the file is not always considered bad practice. as according to official docsSo now, What are the use cases to use
providers
globally?When to use
providers
passing through routes ?According to the official docs of
BlocProvider
influtter_bloc
,follow these steps to passBlocProvider
to the child screen.Creation of
BlocA()
Passing the value of
BlocA
toScreenA()
Make sure this is called from inside the
ChildA()
Now either from
ChildA
orScreenA
retrieve value as: