Flutter Bloc State Set Initial Value To A Dynamic Value From SharedPreferences
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?
Answer
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.
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?