How to change a Flutter app language without restarting the app?

后端 未结 4 1247
忘掉有多难
忘掉有多难 2020-12-31 21:15

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:



        
4条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 21:23

    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.

提交回复
热议问题