flutter - 使用提供程序在 null 上调用了颤振添加方法
问题描述
您好,我想为我的列表添加一些价值。我已经用谷歌搜索了解决方案,但除了初始化我所做的列表之外,我看不到任何其他解决方案。
当我尝试将项目添加到我的AutomaticDateList类时,我收到错误:
在 null 上调用了方法“add”。
接收方: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();
因此,您将“null”作为参数隐式传递,然后items []
被替换为null
值。
只需将代码更改为:
List<AutomaticDate> item;
AutomaticDateList({this.items = []}); // Default value
推荐阅读
- python - 过滤 Lambda 函数输出在 Python 3 中不起作用:参数无效,不是字符串或列
- javascript - 刷新站点后试图阻止新行重置
- r - 如何在 ggplot2 中添加多边形和栅格?ggplot 后的最终绘图中缺少多边形
- python - Python:绘制 .csv 文件的图形并使用鼠标按钮进行切换
- terminal - 导出kid3-cli的语法
- python - 反向查找列表字典中的子字符串
- java - Spring Boot @MockBeans - 如何在多个测试类中使用相同的 bean
- javascript - AJAX 分页和点赞按钮 [SYMFONY 5]
- json - 如何从数据库表中获取数据到 json 格式?拉拉维尔 5.8
- c++ - Cmake:/bigobj:没有这样的文件或目录