Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set initialState from Shared preferences?

I've been trying to add redux to my flutter app

I want to set MaterialUi theme based on user shared preferences

void main() {
  final store = Store<AppState>(
    reducer,
    initialState: AppState.initialState(),
  );

  runApp(MyApp(store: store));
}

I have this Function which returns what user preferences are

  static Future<String> getActiveTheme() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(_activeTheme) ?? "Light";
  }

and my AppState looks like this

class AppState {
  String theme;
  User user;

  AppState(this.theme, this.user);

  AppState.initialState()
      : theme = 'Light',
        user = null;
}

I would want instead of theme: 'Light' to get theme: getActiveTheme()

Thanks in advance

like image 398
Uros Avatar asked Dec 06 '25 19:12

Uros


1 Answers

What you want to do is load the theme as part of your main method. You can then pass the theme you've loaded into your AppState constructors. Not that I've added async to your main method, and moved the setting of theme on your AppState to the parameters.

void main() async {

  var theme = await getActiveTheme();

  final store = Store<AppState>(
    reducer,
    initialState: AppState.initialState(theme),
  );

  runApp(MyApp(store: store));
}

class AppState {

  // ...

  AppState.initialState(this.theme)
      : user = null;
}
like image 69
Tom Alabaster Avatar answered Dec 09 '25 15:12

Tom Alabaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!