Flutter 程序化颤振变化定位

Flutter 程序化颤振变化定位,flutter,localization,Flutter,Localization,我遵循了新的flatter教程()进行本地化,它的效果非常好 但我有一个问题: 当用户点击按钮时,是否可以更改区域设置 MaterialApp( debugShowCheckedModeBanner: false, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales,

我遵循了新的flatter教程()进行本地化,它的效果非常好

但我有一个问题:

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

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

您可以将所需的区域设置传递给MaterialApp。如果为空,应用程序将采用系统语言。通过这种方式,您可以将MaterialApp包装在继承的小部件中,以便从小部件树中的任何位置更改区域设置。这不是一个优雅的解决方案,而是一个简单的解决方案。我的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;
  }
}
MyI18n(
  (locale) => setState(() => this._locale = locale),
  child: MaterialApp(locale: _locale, ...),
),

还有其他方法可以更改区域设置,但我认为这一种方法非常简单。

好的,谢谢您的快速回答!我实施了你的建议。但我有一个问题:如何从树中的小部件更新我的本地文件?如何引用M18“小部件”并调用方法changeLocal?将MyI18n.of(context).changeLocale(locale)与小部件树的任何上下文一起使用。有关InheritedWidget的更多详细说明,请阅读以下文章:感谢您的反馈!它可以工作:)加载我保存在SharedPrefs中的区域设置代码的最佳实践解决方案是什么?在返回继承的小部件之前在我的应用程序中,或者直接在继承的小部件中?我在小部件生成之前设置它。以任何其他方式,文本将在第一帧之后更改。