Search code examples
flutterdartsharedpreferencesbloc

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


I have a bloc cubit to change language from English to Arabic and when I click on change button the language change successfully , but when I'm closing the app and return again the default language is return to work .

this is my language cubit

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

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

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

and this is the usage in main

supportedLocales: AppLocalizationsSetup.supportedLocales,
            localizationsDelegates:
                AppLocalizationsSetup.localizationsDelegates,
            localeResolutionCallback:
                AppLocalizationsSetup.localeResolutionCallback,
            locale: localeState.locale,

so can anyone know how to use shared preference to save the language value when user open the app again .


Solution

  • You can inject the sharedPreferences object into the 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');
    } 
    
    

    Your Cubit has the same API as before , only that now the values are being saved on each state change, and the SharedPreferences must be passed to the constructor.