I have a controller for theme changing like this
class ThemeProvider extends ChangeNotifier {
ThemeMode systemThemeMode = preferences.getBool(Keys.isDarkMode) == null
? ThemeMode.light
: preferences.getBool(Keys.isDarkMode) == true
? ThemeMode.dark
: ThemeMode.light;
bool isDarkMode =
SchedulerBinding.instance.window.platformBrightness.name == "dark"
? true
: false;
toggleTheme(bool isPro) {
if (isPro) {
isDarkMode = !isDarkMode;
preferences.setBool(Keys.isDarkMode, isDarkMode);
systemThemeMode = isDarkMode ? ThemeMode.dark : ThemeMode.light;
notifyListeners();
}
}
}
And this is my main.dart
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => UserController()),
ChangeNotifierProvider(create: (context) => TeamsController()),
ChangeNotifierProvider(create: (context) => MatchListController()),
ChangeNotifierProvider(create: (context) => NewsProvider()),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
],
builder: (context, _) {
final themeProvider =
Provider.of<ThemeProvider>(context, listen: false);
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: LightDarkTheme.lightTheme,
darkTheme: LightDarkTheme.darkTheme,
title: 'CricketR Plus',
themeMode: themeProvider.systemThemeMode,
home: LoginScreen(),
);
});
I am updating value by toggleTheme and I can see its updating by print but theme is going to light to dark. But If I toggle and restart my app then its working perfectly fine.
CodePudding user response:
With Provider.of<ThemeProvider>(context, listen: false)
you specify that you don't want to listen to changes in the provider.
Instead, use this when set themeMode
within MaterialApp
:
themeMode: context.watch<ThemeProvider>().systemThemeMode,
CodePudding user response:
You need to use Consumer widget for that wrap your MaterialApp in it. Then, you can call the ThemeProvider inside the Consumer and update the themeMode of the MaterialApp whenever the theme is toggled.
Here is an example
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => UserController()),
ChangeNotifierProvider(create: (context) => TeamsController()),
ChangeNotifierProvider(create: (context) => MatchListController()),
ChangeNotifierProvider(create: (context) => NewsProvider()),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
],
builder: (context, _) {
return Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: LightDarkTheme.lightTheme,
darkTheme: LightDarkTheme.darkTheme,
title: 'CricketR Plus',
themeMode: themeProvider.systemThemeMode,
home: LoginScreen(),
);
},
);
});