Flutter如何存储在Bloc中本地化的共享递归价值

发布于 2025-01-18 15:55:18 字数 426 浏览 1 评论 0原文

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

class LanguageState extends Equatable {

最终语言环境; const LanguageState({必需 this.locale}); 工厂 LanguageState.initial() => const LanguageState(区域设置: Locale('en', 'US'));

LanguageState copyWith({必需的区域设置语言环境}) =>语言状态(区域设置:区域设置);

@覆盖 // TODO: 实现 props 列出获取道具=> [区域设置]; }

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. this is my code for language state.

class LanguageState extends Equatable {

final Locale 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: implement props
List get props => [locale];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凡尘雨 2025-01-25 15:55:18

您可以将此软件包用于本地化
easylocalization

您可以像这样

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

&将这样的价值存储在共享preference

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

&在您的情况下使用它

    If(local_val != null){

         //do your navigation
   }

you can use this package for localization
easylocalization

you can fetch current locale value like this

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

& store the value like this in sharedpreference

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

& use it in your condition

    If(local_val != null){

         //do your navigation
   }
蓝眸 2025-01-25 15:55:18

您可以使用 hydrated_bloc 保持当前的bloc状态或使 sharedS sharedPreferences 同时喜欢以下 。

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

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

在调用 runapp()之前调用此功能

sharedPreferences.setString("userId", id);

You can use hydrated_bloc to keep the current bloc state or make sharedpreferences synchronously like below .

//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

sharedPreferences.setString("userId", id);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文