如何使用共享首选项通过 bloc 方法保存用户选择的语言

How to use shared preference to save user selected language with bloc approach

我有一个 bloc cubit 可以将语言从英语更改为阿拉伯语,当我点击更改按钮时,语言更改成功,但是当我关闭应用程序并再次 return 时,默认语言是 return 上班 .

这是我的语肘

class LocaleCubit extends Cubit<LocaleState> {
  LocaleCubit() : super(SelectedLocale(Locale('ar')));

  void toArabic() => emit(SelectedLocale(Locale('ar')));

  void toEnglish() => emit(SelectedLocale(Locale('en')));
} 

这是main

中的用法
supportedLocales: AppLocalizationsSetup.supportedLocales,
            localizationsDelegates:
                AppLocalizationsSetup.localizationsDelegates,
            localeResolutionCallback:
                AppLocalizationsSetup.localeResolutionCallback,
            locale: localeState.locale,

谁能知道当用户再次打开应用程序时如何使用共享首选项来保存语言值。

您可以使用shared_preferences的setString方法来保存选择的语言。

setString

Saves a string value to persistent storage in the background.

Future<bool> saveLanguage(String langCode) async {
   SharedPreferences prefs = await SharedPreferences.getInstance();
   // Save the language
   return await prefs.setString('language', langCode);
}

当您要检索保存的语言时:

getString

Reads a value from persistent storage, throwing an exception if it's not a String.

Future<String?> getLanguage() async {
   SharedPreferences prefs = await SharedPreferences.getInstance();
   // Get the language using the key
   return await prefs.getString('language');
}
void toArabic() {
   emit(SelectedLocale(Locale('ar')));
   saveLanguage('ar');
}

void toEnglish() {
   emit(SelectedLocale(Locale('en')));
   saveLanguage('en');
}

您可以将 sharedPreferences 对象注入 Cubit。

class LocaleCubit extends Cubit<LocaleState> {
  final SharedPreferences _preferences;
LocaleCubit(this._preferences) : super(SelectedLocale(Locale(_preferences.getString('locale')??'ar')));
// Here we initialize the object to the last saved locale and default to 'ar' if there is none


// Method that saves and emits the new locale
  void _changeLocale(String locale) { 
_preferences.setString('locale',locale);
emit(SelectedLocale(Locale(locale)));
}
  void toEnglish() => _changeLocale'en');
  void toArabic() => _changeLocale('ar');
} 

您的 Cubit 和以前一样 API,只是现在每次状态更改时都会保存值,并且必须将 SharedPreferences 传递给构造函数。