Reputation: 180
I have declared MultipleProviders in my widget and i want to use it to change the color of the App by assaining the variable to the ThemeData Primary swatch but it's giving me this error related to provider . and i have use in other widgets and it's working .i think i am getting this error bacause i am using it in the same widget how i can solve it ?
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var u = Provider.of<prov>(context);
return MultiProvider(
providers: [ChangeNotifierProvider(create: (_)=>prov())],
child: GetMaterialApp(
theme: ThemeData(primarySwatch: u.col),
title: 'Material App',
home: f(),
),
);
}
}
this is the error
Error: Could not find the correct Provider above this MyApp Widget
This happens because you used a BuildContext
that does not include the provider
of your choice. There are a few common scenarios:
You added a new provider in your main.dart
and performed a hot-reload.
To fix, perform a hot-restart.
The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then other routes will not be able to access that provider.
You used a BuildContext
that is an ancestor of the provider you are trying to read.
Make sure that MyApp is under your MultiProvider/Provider. This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
consider using builder
like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
Upvotes: 2
Views: 5098
Reputation: 7726
You're getting the error because the context
you're using does not have access to the provider
.
The solution is like it says in the error message: you can use a builder
instead of a child
property for your provider
. That creates a new context
that reads the provider
created.
You should change your build
method to this.
Widget build(BuildContext context) {
return MultiProvider(
providers: [ChangeNotifierProvider(create: (_)=>prove())],
//From here is where you make the change
builder: (context, child) {
var u = Provider.of<prov>(context);
return GetMaterialApp(
theme: ThemeData(primarySwatch: u.col),
title: 'Material App',
home: f(),
),
);
}
Upvotes: 6