Nagween Jaffer
Nagween Jaffer

Reputation: 180

Using Provider in the same widget in flutter

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:

Upvotes: 2

Views: 5098

Answers (1)

Victor Eronmosele
Victor Eronmosele

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

Related Questions