Home > Net >  Flutter Locale property
Flutter Locale property

Time:04-23

Tryed to make the Provider LocaleProvider. But get the Error "Non-nullable instance field '_locale' must be initialized. Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'." making it "late" gets me the error "The following LateError was thrown building Builder(dirty, dependencies: [_InheritedProviderScope]): LateInitializationError: Field '_locale@23001738' has not been initialized."

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();
  }
}

CodePudding user response:

Add a constructor

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();
  }
}
  • Related