I have this code:
MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => CubitExample(),
),
],
child: MaterialApp(
home: Home(),
),
);
It’s working fine, I have many cubits/blocs so I decided to move the providers list to a separate class:
MultiBlocProvider(
providers: BlocProviders.blocs(),
child: MaterialApp(
home: Home(),
),
);
// The class
class BlocProviders {
static List<BlocProvider> blocs() {
return <BlocProvider>[
BlocProvider(
create: (context) => CubitExample(()),
),
];
}
}
Now the usual bloc error is thrown:
ProviderNotFoundException (Error: Could not find the correct Provider<ExampleCubit> above this BlocBuilder<ExampleCubit, ExampleState> Widget
I don’t know why the error is thrown when I try the second code, why the error is thrown?
2
Answers
It is really strange why this is behaving this way!!, I tried all possible work arounds.
Finally found a way around to this by using
getter
.Replace your
function
withgetter
. This should do the work.And call it as
I think I managed to get some insights,
Whenever we wrap a widget with
MultiBlocProvider
, we give the list of Providers in it with a child widget.So I looked into the implementation of
MultiBlocProvider
and I found that it accepts a List of type BlocProviderSingleChildWidget and it is a mixin defined onSingleChildWidget
which means that we can not use List.Now in your case you defined the widget class like this:
and your bloc class like this:
In this you have created list of type
List<BlocProvider>
, which is not aBlocProviderSingleChildWidget
. Therefore it was showing you the error you were talking about.One person answered the question by using the
getter
method instead of static function, and it was working because he didn’t give any type to the list(it was dynamic), therefore the error was gone.Now, If you want to use your class and functions like you’ve mentioned, you can pretty much use it by giving it dynmic type like this:
Hope it solved all your issues and question related to it. Further, if you want to know about it you can look at the implementation of
MultiBlocProvider
.