Flutter 以编程方式更改本地化

Flutter change Localization programatically

我遵循了新的本地化 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(),
      );

您可以将您希望的区域设置传递给 MaterialApp。如果为空,应用程序将采用系统语言。通过这种方式,您可以将 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 and/or a Bloc 以相同的方式完成,但代码更少。)