如何从共享首选项中设置initialState?

问题描述 投票:0回答:1

我一直在尝试将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()

提前致谢

redux dart flutter sharedpreferences
1个回答
1
投票

你想要做的是加载主题作为你的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;
}
© www.soinside.com 2019 - 2024. All rights reserved.