flutter add sharedpreferences to SwitchMode

32 Views Asked by At

I make Switch Dark Mode to my App from lesson in YouTube.

https://www.youtube.com/watch?v=iCbakAjWnaI

its work fine but when I close the app it's not save set dark or light.

how can I add SharedPreferences to it?

1

There are 1 best solutions below

1
Mobterest Studio On
  • Add the shared_preferences dependency to your flutter application.
  • Create a function that sets and gets the value of key 'darktheme'.

setter method

    Future<void> setDarkTheme(bool isDarkMode) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool('darktheme', isDarkMode);
  }

getter method

Future<bool> getDarkTheme() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool('darktheme') ?? false;
  }

In the user interface proceed to use the methods:

To view:

themeMode: getDarkTheme() ? ThemeMode.dark : ThemeMode.light,

To update, maybe using a SwitchListTile:

SwitchListTile(
      tileColor: Colors.blue,
      title: const Text('Set to Dark mode'),
      value: getDarkTheme(),
      onChanged:(bool? value) { 
     setDarkTheme(value!);

},
    ),