Art
Art

Reputation: 227

How I can give the Switch in Flutter the right value after toggled and restart the app?

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

Answers (1)

Raouf Rahiche
Raouf Rahiche

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

Related Questions