Reputation: 227
I have a switch with that I switching between light theme and dark theme. Switch value true = dark theme. Switch value false = light. And the default is false. If I switch from false to true the theme switches to dark so far so good. But if I restart the app is the switch false and the dark theme is shown.
bool _switchValue = false;
void _changeThemeInOpp(bool switchValue) {
setState(() {
_switchValue = switchValue;
});
if (_switchValue == true) {
DynamicTheme.of(context).setBrightness(Brightness.dark);
} else {
DynamicTheme.of(context).setBrightness(Brightness.light);
}
}
new Switch(
value: _switchValue,
onChanged: (bool switchValue) {
_changeThemeInOpp(switchValue);
}),
How I can restart the app and the switch have the right value?
Upvotes: 1
Views: 2493
Reputation: 31356
You need to save the _switchValue
in the disk using something like shared_preferences
for more information see :
Storing key-value data on disk
save the value when you change it :
void _changeThemeInOpp(bool switchValue) async{
// save new value
final _switchValue= await SharedPreferences.getInstance();
_switchValue.setInt('Value', switchValue);
setState(() {
_switchValue = switchValue;
});
if (_switchValue == true) {
DynamicTheme.of(context).setBrightness(Brightness.dark);
} else {
DynamicTheme.of(context).setBrightness(Brightness.light);
}
}
Upvotes: 4