Flutter bloc state set initial value to a dynamic value from sharedPreferences

Issue

I want to set the initial state to a value persistantly saved with shared_preferences. The value is the language of my app and I set the locale of my app inside of the main.dart file with state.language.

import 'storageUtils.dart';

class LanguageState {
  //TODO: set initial language to language stored with shared_preference
  LanguageState({this.language = LanguagePreference.getLanguage()});
  final String language;

  LanguageState copyWith({
    String? language,
  }) {
    return LanguageState(language: language ?? this.language);
  }
}

These are my storageUtils.dart that I use to change and get the language:

class LanguagePreference {
  static late SharedPreferences _preferences;

  static Future init() async =>
      _preferences = await SharedPreferences.getInstance();

  static Future changeLanguage(String language) async =>
      await _preferences.setString("language", language);

  static String getLanguage() => _preferences.getString("language") ?? "en";
}

But because the getLanguage function isn’t a constant I can’t initialize the state with the dynamic value of the getLanguage function. Is there another way to initialize the language state with the dynamic value of the getLanguage function?

Solution

But because the getLanguage function isn’t a constant I can’t initialize the state with the dynamic value of the getLanguage function.

Small correction: you cannot use the function as a default in your method call.

Is there another way to initialize the language state with the dynamic value of the getLanguage function?

Sure. You can for example pass it in where you create the state:

LanguageBloc(String language) : super(LanguageState(language));

so wherever you create your bloc, you can just call your method:

runApp(
    MultiBlocProvider(
      providers: [
        BlocProvider<LanguageBloc>(
           create: (context) => LanguageBloc(LanguagePreference.getLanguage())
        ),
      ]
    ...

Assuming you have initialized your LanguagePreference before that.

Answered By – nvoigt

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.