0

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]; }

Sheikh Raj
  • 41
  • 1
  • 7

2 Answers2

0

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
   }
  • i have already implemented bloc for localization, here i wanna know how to use shared preference in the bloc for initializing language if user already set language. – Sheikh Raj Apr 04 '22 at 12:11
0

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);
Ilyas Arafath
  • 511
  • 7
  • 13