使用提供程序在 null 上调用了 flutter add 方法

flutter add method was called on null using provider

您好,我想为我的清单添加一些价值。我已经在谷歌上搜索了解决方案,但除了初始化我所做的列表之外,我看不到任何其他解决方案。

当我尝试将项目添加到我的 AutomaticDateList class 时,出现错误:

The method 'add' was called on null.
Receiver: null
Tried calling: add(Instance of 'AutomaticDate')

这是包含列表的 class。

class AutomaticDateList with ChangeNotifier {
List<AutomaticDate> items = [];  // here I inialize

AutomaticDateList({this.items});

void addToList(AutomaticDate automaticDate) {
items.add(automaticDate);
notifyListeners();
}

 List<AutomaticDate> get getItems => items;
}

这是我要添加到列表中的项目。

class AutomaticDate with ChangeNotifier {
String date;
String enterDate;
String leaveDate;
String place;

AutomaticDate({this.date, this.enterDate, this.leaveDate, this.place});

这里我使用页面小部件中的提供程序调用方法

void onGeofenceStatusChanged(Geofence geofence, GeofenceRadius geofenceRadius,
  GeofenceStatus geofenceStatus) {
geofenceController.sink.add(geofence);
AutomaticDate automaticDateData = AutomaticDate();

automaticDateData.place = geofence.id;
automaticDateData.date = DateFormat("dd-mm-yyyy").format(DateTime.now());
if (geofenceStatus == GeofenceStatus.ENTER) {
  widget.enterDate = DateFormat("HH:mm:ss").format(DateTime.now());
} else {
  automaticDateData.leaveDate =
      DateFormat("HH:mm:ss").format(DateTime.now());
  automaticDateData.enterDate = widget.enterDate;
  widget.list.add(automaticDateData);

  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    AutomaticDateList automaticDateList =
        Provider.of<AutomaticDateList>(context, listen: false);
    automaticDateList.items.add(automaticDateData); // Here I add the data and get error "add was called on null"
    print(automaticDateList.getItems); 
  });
}
}

问题出在初始化:

List<AutomaticDate> items = [];  // here I inialize

AutomaticDateList({this.items});

你设置了一个默认值,但是你在构造函数中使用了"auto-assign" 语法,表示在参数中传递 的项目将会分配到 class.

的 属性 项中

您正在使用此代码实例化 class:

AutomaticDate automaticDateData = AutomaticDate();

因此,您将“null”作为参数隐式传递,然后 items [] 被替换为 null 值。

只需将代码更改为:

List<AutomaticDate> item;

AutomaticDateList({this.items = []}); // Default value