how do i use provider in this situation

156 Views Asked by At

I want to create a change app theme mode and I saw a way of creating it with Provider but I'm new to Provider. For Example, I want to add some codes like this

highlight code (the highlighted code)

in my main which consists of many routes

my main

2

There are 2 best solutions below

0
On

You want to change the theme of the app, then you need to move provider up so it can cover the widget (App in this case) state, You could do something like this in your main method :

runApp(ChangeNotifierProvider(

    create: (context) => ThemeProvider(),
    child:MyApp()

);

now in the case of children you could simply call provider in the build method like this

Widget build(){
   var themeProvider = Provider.of<ThemeProvider>(context);
}

or you could use the consumer widget

Consumer<ThemeProvider>(
builder: (context, provider, child) {
//return something
}

)
0
On

I suggest you to move your ChangeNotifierProvider to your runApp() method

runApp(
        ChangeNotifierProvider<ThemeProvider>(
          create: (_) => ThemeProvider(),
          child: MyApp(),
        ),
      ),

Where your MyApp() is just all of your app extracted to its own widget.

Then you can actually easily access it as you wish with a Consumer widget on your build method.

return Consumer<ThemeProvider>(
    builder: (BuildContext context, ThemeProvider provider, _) {
    return MaterialApp(
     theme: provider.myTheme,
     ... 
   );
  }
)