In the settings page of my app, I would like to add an option that controls the app language.
I can set the language before starting the app like this:
You can wrap the MaterialApp
widget with a ChangeNotifierProvider
and a Consumer
widgets and control the language from the model.
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
builder: (context) => MainModel(context: context),
child: Consumer(builder: (context, mainModel, child) {
return MaterialApp(
locale: Locale(mainModel.preferredLanguageCode),
....
On the MainModel
, all you need to do is change the preferredLanguageCode
variable to whatever you want ('en', 'ar', 'es', etc). Don't forget to call NotifyListeners()
once you change the language.
This and the other answer have only one problem: Any context
above MaterialApp
can't get the device language (for example when the app is started for the first time) with Localizations.localeOf(context)
. This method required a context
bellow MaterialApp
.
To fix this issue, I used this plugin to get the device language without the need of a context
.
Once the app starts, you can change the language any way you want that this approach will work. I also use SharedPreferences
to store the preferred language once the user changes it.