How to store theme in shared preferences in flutter

3,203

You can simply save/retrieve a theme id that can be used to identify wich theme is selected when starting the app, something like

class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {

  // at this point you should be already have a mainSharedPreferences already initialized, could be in SplashScreen
  // to prevent async calls in the initialState

  @override
  ThemeState get initialState => ThemeState(
      themeData: appThemeData[
          MyApp.mainSharedPreferences.getInt("selectedThemeIndex") ??
              AppTheme.GreenLight]);

  @override
  Stream<ThemeState> mapEventToState(
    ThemeEvent event,
  ) async* {
    if (event is ThemeChanged) {
      await _persistTheme(event.theme);
      yield ThemeState(themeData: appThemeData[event.theme]);
    }
  }

  _persistTheme(AppTheme theme) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt("selectedThemeIndex", theme.index);
    // or you could save the theme.toString()
    // prefs.setString("selectedTheme", theme.toString());
  }
}

How to prepare SharedPreferences to avoid the Future<SharedPreferences>

class MyApp extends StatefulWidget {
  static SharedPreferences mainSharedPreferences;

  @override
  _MyAppState createState() => _MyAppState();
}



class _MyAppState extends State<MyApp> {

_loadApp() async {
    MyApp.mainSharedPreferences = await SharedPreferences.getInstance();
    // you can load here any other data or external data that your app might need
  }

  @override
  void initState() { 
    super.initState();
    _loadApp();
  }

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: [
      // ...

Then you can use it anywhere from your app like so

// to save value
MyApp.mainSharedPreferences.setInt("selectedThemeIndex", value);

// to get the saved value
MyApp.mainSharedPreferences.getInt("selectedThemeIndex");
Share:
3,203
Rutvik Gumasana
Author by

Rutvik Gumasana

Updated on December 05, 2022

Comments

  • Rutvik Gumasana
    Rutvik Gumasana over 1 year

    Here I've one screen where I've some button when I press the button it will change the color of application but it will reset when I restart the app. I want that it will not reset until I am changing the color from the App. so for that, I want to store THemedata in shared preferences and I want to get theme data from shared preferences so whenever I restart the app it needs to take the theme from Shared preferences.

    Here is some code I've tried,

    ThemeBloc.dart

    class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {
      @override
      ThemeState get initialState =>
          ThemeState(themeData: appThemeData[AppTheme.GreenLight]);
    
      @override
      Stream<ThemeState> mapEventToState(
        ThemeEvent event,
      ) async* {
        if (event is ThemeChanged) {
          yield ThemeState(themeData: appThemeData[event.theme]);
        }
      }
    }
    

    ThemeEvent.dart

    abstract class ThemeEvent extends Equatable {
      ThemeEvent([List props = const <dynamic>[]]) : super(props);
    }
    
    class ThemeChanged extends ThemeEvent {
      final AppTheme theme;
    
      ThemeChanged({
        this.theme,
      }) : super([theme]);
    }
    

    ThemeState.dart

    @immutable
    class ThemeState extends Equatable {
      final ThemeData themeData;
    
      ThemeState({
        @required this.themeData,
      }) : super([themeData]);
    }
    

    AppTheme.dart

    enum AppTheme {
      GreenLight,
      GreenDark,
      BlueLight,
      BlueGrey,
      Amber,
    }
    
    final appThemeData = {
      AppTheme.GreenLight: ThemeData(
        brightness: Brightness.light,
        primaryColor: Colors.teal,
      ),
      AppTheme.GreenDark: ThemeData(
        brightness: Brightness.light,
        primaryColor: Colors.orange,
      ),
    };
    
    • imtoori
      imtoori over 4 years
      You can serialize/deserialize it to json
  • Rutvik Gumasana
    Rutvik Gumasana over 4 years
    and how can i store theme id?? and from where i've to get theme ID?
  • Slah Layouni
    Slah Layouni over 4 years
    You can define you own theme ids, example id: 1 => theme1, etc..
  • Slah Layouni
    Slah Layouni over 4 years
    @RutvikGumasana i edited my answer, that can get you started
  • Rutvik Gumasana
    Rutvik Gumasana over 4 years
    Thank you so much i'll try the code and let you know :)
  • avechuche
    avechuche over 4 years
    @SlahLayouni Hi, I have a question with your solution. How do I load SharedPreferences synchronously? I have the same problem, I want to load language and theme from sharedpreferences and save it in initialState. thx!
  • Rutvik Gumasana
    Rutvik Gumasana over 4 years
    and please @SlahLayouni can you please tell me how I store theme in shared preference
  • Sunoj Vijayan
    Sunoj Vijayan about 4 years
    when I call this appThemeData[ MyApp.mainSharedPreferences.getInt("selectedThemeIndex") ?? AppTheme.GreenLight]); I get the following error The method 'getInt' was called on null. Can someone help please?