繁体   English   中英

Flutter 如何在 bloc 中存储用于本地化的 sharepreferences 值

[英]Flutter how to store sharepreferances value for localization in bloc

我已经使用 bloc 模式实现了本地化,但现在我想将语言的值存储在 sharepreferences 中,这样下次如果用户已经选择了语言,它将跳过 select 语言流并从本地存储中获取它。 这是我的语言代码 state。

class LanguageState extends Equatable {

最终的 Locale 语言环境; const LanguageState({required this.locale}); factory LanguageState.initial() => const LanguageState(locale: Locale('en', 'US'));

LanguageState copyWith({required Locale locale}) => LanguageState(locale: locale);

@override // TODO: 实现 props List get props => [locale]; }

您可以使用此 package 进行本地化easylocalization

您可以像这样获取当前语言环境值

var currentLocale = EasyLocalization.of(context)?.locale ?? 'en';

并将这样的值存储在 sharedpreference 中

await SharedPref.write("local_val", //your value);

并根据您的情况使用它

    If(local_val != null){

         //do your navigation
   }

您可以使用hydred_bloc来保留当前的 bloc state或像下面这样同步设置共享首选项。

//global variable of shared pref
static late SharedPreferences sharedPreferences;

  //making sharedPreference synchronously
  Future<void> initializeSharedPref() async {
    sharedPreferences = await SharedPreferences.getInstance();
  }

在调用runApp()之前调用这个 function ,然后在你想要 sharedpref 实例的地方只需像这样调用全局变量 static

sharedPreferences.setString("userId", id);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM