Micipsa
Micipsa

Reputation: 107

Get value from shared preference in Flutter

Dear Stackoverflow community,

I want to get the value of locale language in my app. I'm using shared preference and I want to use the locale language value in a another page, but I don't find the way to call the value:

This is my page main.dart with :

    class TranslatePreferences implements ITranslatePreferences
{
  static const String _selectedLocaleKey = 'selected_locale';

  @override
  Future<Locale> getPreferredLocale() async
  {
    final preferences = await SharedPreferences.getInstance();

    if(!preferences.containsKey(_selectedLocaleKey)) return null;

    var locale = preferences.getString(_selectedLocaleKey);
    return localeFromString(locale);

  }


  @override
  Future savePreferredLocale(Locale locale) async
  {
    final preferences = await SharedPreferences.getInstance();

    await preferences.setString(_selectedLocaleKey, localeToString(locale));

  }


}

If I understand well I have to use the getPreferredLocale() in my other page but even I import the main.dart I can get the getPreferredLocale() in lang.dart page:

class lang{
string lang=TranslatePreferences.getPreferredLocale();
print(lang);

}

Thanks for your help.

Upvotes: 0

Views: 582

Answers (1)

Zvi Karp
Zvi Karp

Reputation: 3904

at the bottom on the TranslatePreferences file (outside the classs) add:

TranslatePreferences translatePreferences = TranslatePreferences();

then in the lang class you can use it:

string lang=translatePreferences.getPreferredLocale();

Upvotes: 1

Related Questions