Reputation: 13
My flutter app doesnt listen user's preferences changes at dark theme feature. I need to hard restart my app to reflect the changes.
How to make my flutter theme change instantly once I turn on / off the dark theme in device setting?
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
brightness: Brightness.light
),
darkTheme: ThemeData(
brightness: Brightness.dark
),
themeMode: ThemeMode.system,
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
Thanks
Upvotes: 1
Views: 891
Reputation: 66
I would recommend you give this plugin Adaptive Chameleon Theme a try. It is designed to help you switch theme modes with ease be it from light to dark or even utilising the default user defined device theme.
Like so:
// sets theme mode to dark
AdaptiveChameleonTheme.of(context).changeThemeMode(dark: true);
// sets theme mode to light
AdaptiveChameleonTheme.of(context).changeThemeMode(dark: false);
// sets theme mode to system default
AdaptiveChameleonTheme.of(context).changeThemeMode(dynamic: true);
It also comes with the added benefit of allowing you to change the theme colours if you need to.
AdaptiveChameleonTheme.of(context).setTheme(AppThemes.LightRed);
AdaptiveChameleonTheme.of(context).setTheme(AppThemes.LightBlue);
The selections are stored in shared preferences and persisted in the device memory.
Full disclosure, I am the developer of the plugin so you can consider this a shameless plug. However, I too faced similar challenges in the past leading me to develop this quick and easy to use solution.
Upvotes: 1
Reputation: 835
To see the change you need two things, use StatefulWidget
and call setState
everytime user change theme.
IconButton(
onPressed: () {
setState(() {
functionToChangeTheme();
});
},
icon: Icon(Icons.add),
)
Upvotes: 0