首页 > 解决方案 > 使用提供程序在 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); 
  });
}
}

标签: flutterdartflutter-provider

解决方案


问题在于初始化:

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

推荐阅读