Flutter bloc 状态将初始值设置为来自 sharedPreferences 的动态值

Flutter bloc state set initial value to a dynamic value from sharedPreferences

我想将初始状态设置为使用 shared_preferences 永久保存的值。该值是我的应用程序的语言,我在 main.dart 文件中使用 state.language.

设置了我的应用程序的语言环境
import 'storageUtils.dart';

class LanguageState {
  //TODO: set initial language to language stored with shared_preference
  LanguageState({this.language = LanguagePreference.getLanguage()});
  final String language;

  LanguageState copyWith({
    String? language,
  }) {
    return LanguageState(language: language ?? this.language);
  }
}

这些是我用来更改和获取语言的 storageUtils.dart

class LanguagePreference {
  static late SharedPreferences _preferences;

  static Future init() async =>
      _preferences = await SharedPreferences.getInstance();

  static Future changeLanguage(String language) async =>
      await _preferences.setString("language", language);

  static String getLanguage() => _preferences.getString("language") ?? "en";
}

但是因为 getLanguage 函数不是常量,所以我无法使用 getLanguage 函数的动态值初始化状态。是否有另一种方法可以使用 getLanguage 函数的动态值来初始化语言状态?

But because the getLanguage function isn't a constant I can't initialize the state with the dynamic value of the getLanguage function.

小更正:您不能在方法调用中将该函数用作默认值。

Is there another way to initialize the language state with the dynamic value of the getLanguage function?

当然可以。例如,您可以将其传递到 创建 状态的位置:

LanguageBloc(String language) : super(LanguageState(language));

所以无论你在哪里创建你的集团,你都可以调用你的方法:

runApp(
    MultiBlocProvider(
      providers: [
        BlocProvider<LanguageBloc>(
           create: (context) => LanguageBloc(LanguagePreference.getLanguage())
        ),
      ]
    ...

假设您在此之前已经初始化了 LanguagePreference