如何从“共享”偏好设置中设置initialState?

时间:2019-03-26 16:19:28

标签: redux dart flutter sharedpreferences

我一直试图将redux添加到我的flutter应用程序中

我想基于用户共享的偏好设置MaterialUi主题

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

  runApp(MyApp(store: store));
}

我有这个函数,它返回什么是用户喜好

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

我的AppState看起来像这样

class AppState {
  String theme;
  User user;

  AppState(this.theme, this.user);

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

我希望代替theme: 'Light'获得theme: getActiveTheme()

预先感谢

1 个答案:

答案 0 :(得分:0)

您要做的是将主题作为main方法的一部分加载。然后,您可以将已加载的主题传递到AppState构造函数中。并非我已将async添加到您的main方法中,并将theme上的AppState的设置移到了参数上。

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;
}