flutter add method was called on null using provider


Hello I want to add some value to my list. I have already googled for solutions but I can’t see any other solutions besides initializing the list which I did.

When I try to add an item to my AutomaticDateList class I get the error:

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

Here is the class with the list in it.

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


void addToList(AutomaticDate automaticDate) {

 List<AutomaticDate> get getItems => items;

This is the item I want to add to the list.

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

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

Here I call the method using the provider inside a page widget

void onGeofenceStatusChanged(Geofence geofence, GeofenceRadius geofenceRadius,
  GeofenceStatus geofenceStatus) {
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 =
  automaticDateData.enterDate = widget.enterDate;

  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"


The problem is in the initialization:

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


You set a default value, but you are using the "auto-assign" sintax in the constructor, saying that items passing in the parameters are going to be assigned in the items property of the class.

You are instantiating the class using this code:

AutomaticDate automaticDateData = AutomaticDate();

So, you are passing "null" implicitly as parameter, then items [] got replaced with null value.

Just change the code to:

List<AutomaticDate> item;

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

Answered By – Mou

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *