你好,我想给我的列表添加一些值。我已经在谷歌上搜索了解决方案,但除了初始化列表之外,我看不到任何其他解决方案。
当我尝试将项目添加到AutomaticDateList类时,我会得到错误:
方法"add"是在null上调用的
接收方:null
尝试调用:add("AutomaticDate"的实例(
这是包含列表的类。
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});
您设置了一个默认值,但您使用的是"自动分配">sintax,表示参数中传递的项将在类的items属性中赋值。
您正在使用以下代码实例化类:
AutomaticDate automaticDateData = AutomaticDate();
所以,你正在通过";空";隐式地作为参数,则items []
被替换为null
值。
只需将代码更改为:
List<AutomaticDate> item;
AutomaticDateList({this.items = []}); // Default value