I'm looking to make a button that can change the theme of my app, this button would be located in the settings page. Unfortunately, I haven't found a solution yet, all I could find on the internet was ways to switch themes dynamically.
I'm looking to make a button that can change the theme of my app, this button would be located in the settings page. Unfortunately, I haven't found a solution yet, all I could find on the internet was ways to switch themes dynamically.
The answer above is correct. Here is some code to help you visualize the solution.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(
MultiProvider(
providers: [
// Used MultiProvider incase you have other providers
ChangeNotifierProvider<ThemeDataProvider>(
create: (_) => ThemeDataProvider(),
),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
ThemeDataProvider themeDataProvider = Provider.of(context);
// Pull the theme data from the provider and make a few modification
// The modifications are for illustration only. Not required.
final ThemeData currentTheme = themeDataProvider.themeData.copyWith(
scaffoldBackgroundColor: themeDataProvider.isDarkTheme ? Colors.yellow[700] : Colors.yellow[300],
appBarTheme: themeDataProvider.themeData.appBarTheme,
cardTheme: themeDataProvider.themeData.cardTheme,
);
return MaterialApp(
color: Colors.yellow[100],
title: 'MyApp',
theme: currentTheme, //set your theme
initialRoute: setupRoute,
onGenerateRoute: Router.generateRoute,
);
}
}
class ThemeDataProvider with ChangeNotifier {
bool _useDarkTheme;
SharedPreferences _prefs;
ThemeDataProvider() {
_useDarkTheme = false;
_loadPrefs();
}
ThemeData get themeData => _useDarkTheme ? myThemeDark : myThemeLight; //MyTheme... is defined by you
bool get isDarkTheme => _useDarkTheme;
void toggleTheme() {
_useDarkTheme = !_useDarkTheme;
_savePrefs();
notifyListeners();
}
//The reset is just incase you want to save the selected theme for the next time your app is run.
_initPrefs() async {
if (_prefs == null) {
_prefs = await SharedPreferences.getInstance();
}
}
_loadPrefs() async {
await _initPrefs();
_useDarkTheme = _prefs.getBool("useDarkMode") ?? true;
notifyListeners();
}
_savePrefs() async {
await _initPrefs();
await _prefs.setBool("useDarkMode", _useDarkTheme);
}
}
It is really staight forward once you use it a few times.
Good luck!
If you have single page its very easy just use Setstate to change the color but if you want to change multiple widgets/pages I suggest learning Provider-> ChangeNotifierProvider. Because every page needs to listen to the color that's currently selected and rebuild the widget if the color changes.
install get package getx and then you can switch your moods like this :
Get.isDarkMode? Get.changeTheme(ThemeData.light()):Get.changeTheme(ThemeData.dark());