Flutter如何在块中存储本地化的shareperferences值

beq87vna  于 2023-01-06  发布在  Flutter
关注(0)|答案(2)|浏览(126)

我已经实现了本地化与块模式,但现在我想存储语言的值在shareperferences,以便下一次如果这用户已经选择语言它将跳过选择语言流和fetch它从本地存储.这是我的代码为语言状态.

class LanguageState extends Equatable {

最终语言环境;常量语言状态({需要此.locale});工厂语言状态。初始值()=〉常量语言状态(区域设置:区域设置('en','US'));
语言状态copyWith({必需的区域设置区域设置})=〉语言状态(区域设置:地点);
@覆盖//待办事项:实现props列表获取props =〉[语言环境];}

mzsu5hc0

mzsu5hc01#

你可以使用这个软件包进行本地化easylocalization
你可以像这样获取当前的语言环境值

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

&在sharedpreference中存储这样的值

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

&在你的情况下使用它

If(local_val != null){

         //do your navigation
   }
0dxa2lsx

0dxa2lsx2#

您可以使用hydrated_bloc来保持当前的块状态,或者像下面这样使sharedpreferences同步。

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

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

在调用**runApp()**之前调用此函数,然后在需要sharedpref示例的地方调用全局静态变量,如下所示

sharedPreferences.setString("userId", id);

相关问题