简体   繁体   English

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

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

i have implemented localization with bloc pattern but now I wanna store the value of language in sharepreferences so that next time if the user already selected language it will skip select language flow and fetch it from local storage.我已经使用 bloc 模式实现了本地化,但现在我想将语言的值存储在 sharepreferences 中,这样下次如果用户已经选择了语言,它将跳过 select 语言流并从本地存储中获取它。 this is my code for language state.这是我的语言代码 state。

class LanguageState extends Equatable {

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

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

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

you can use this package for localization easylocalization您可以使用此 package 进行本地化easylocalization

you can fetch current locale value like this您可以像这样获取当前语言环境值

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

& store the value like this in sharedpreference并将这样的值存储在 sharedpreference 中

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

& use it in your condition并根据您的情况使用它

    If(local_val != null){

         //do your navigation
   }

You can use hydrated_bloc to keep the current bloc state or make sharedpreferences synchronously like below.您可以使用hydred_bloc来保留当前的 bloc state或像下面这样同步设置共享首选项。

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

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

Call this function before calling the runApp() , Then where you want sharedpref instance just call the global static variable like this在调用runApp()之前调用这个 function ,然后在你想要 sharedpref 实例的地方只需像这样调用全局变量 static

sharedPreferences.setString("userId", id);

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

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