颤振语言环境 属性

Flutter Locale property

已尝试制作 Provider LocaleProvider。但是得到错误“必须初始化不可为空的实例字段'_locale'。 尝试添加一个初始化表达式,或一个初始化它的生成构造函数,或将其标记为 'late'。”使其“迟到”让我得到错误“The following LateError was thrown building Builder(dirty, dependencies: [_InheritedProviderScope]) : LateInitializationError:字段“_locale@23001738”尚未初始化。“

class LocaleProvider extends ChangeNotifier {
  Locale _locale;

  Locale get locale => _locale;

  void setLocale(Locale locale) {
    if (!L10n.all.contains(locale)) return;

    _locale = locale;
    notifyListeners();
  }

  void clearLocale() {
    _locale = const Locale('en');
    notifyListeners();
  }
}

添加构造函数

class LocaleProvider extends ChangeNotifier {
  Locale _locale;

  LocaleProvider(this._locale);//constructor for field initialization

  Locale get locale => _locale;

  void setLocale(Locale locale) {
    if (!L10n.all.contains(locale)) return;

    _locale = locale;
    notifyListeners();
  }

  void clearLocale() {
    _locale = const Locale('en');
    notifyListeners();
  }
}