【问题标题】:Flutter change Localization programaticallyFlutter 以编程方式更改本地化
【发布时间】:2021-07-10 08:51:44
【问题描述】:

我按照新的 Flutter 教程 (https://flutter.dev/docs/development/accessibility-and-localization/internationalization) 进行本地化,它就像一个魅力。

但我有一个问题:

用户点击按钮时是否可以更改区域设置?

MaterialApp(
        debugShowCheckedModeBanner: false,
        localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
        title: "MyApp",
        theme: ct.theme,
        home: MyHomePage(),
      );

【问题讨论】:

    标签: flutter localization


    【解决方案1】:

    您可以将您希望的语言环境传递给MaterialApp。如果为 null,则应用程序将采用系统语言。这样,您可以将MaterialApp 包装在InheritedWidget 中,以便从小部件树中的任何位置更改语言环境。这不是一个优雅但简单的解决方案。我的InheritedWidget 看起来像这样:

    class MyI18n extends InheritedWidget {
      final Function(Locale) _localeChangeCallback;
    
      const MyI18n(
          this._localeChangeCallback,{
        Key key,
        @required Widget child,
      })  : assert(child != null),
            super(key: key, child: child);
    
      static MyI18n of(BuildContext context) {
        return context.dependOnInheritedWidgetOfExactType<MyI18n>();
      }
    
      void changeLocale(Locale locale) {
        _localeChangeCallback?.call(locale);
      }
    
      @override
      bool updateShouldNotify(MyI18n old) {
        return true;
      }
    }
    

    您还可以将语言环境保存在 InheritedWidget 中,以便在 updateShouldNotify 中使用它:)

    您的MaterialApp 将如下所示:

    MyI18n(
      (locale) => setState(() => this._locale = locale),
      child: MaterialApp(locale: _locale, ...),
    ),
    

    使用:MyI18n.of(context).changeLocale(locale)

    还有其他方法可以更改语言环境,但我认为这个方法非常简单。 (您可以通过使用Provider 和/或Bloc 以更少的代码执行此操作。)

    【讨论】:

    • 好的,感谢您的快速回答!我实施了你的提议。但我对此有一个问题:如何从树内的小部件更新我的本地?如何引用 M18“Widget”并调用方法 changeLocal?
    • 将 MyI18n.of(context).changeLocale(locale) 与小部件树的任何上下文一起使用。 InheritedWidget更详细的解释可以阅读以下文章:api.flutter.dev/flutter/widgets/InheritedWidget-class.html
    • 感谢您的反馈!它有效:)
    • 加载我保存在 SharedPrefs 中的语言环境代码的最佳实践解决方案是什么?在返回继承的小部件之前在我的应用程序中还是直接在继承的小部件中?
    • 我在构建小部件之前设置了它。以任何其他方式,文本会在第一帧之后发生变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多