flutterbug98
flutterbug98

Reputation: 121

Flutter: The method 'add' was called on null

So I have created a simple notification class as follows:

class NamedNotification{
  String title;
  DateTime scheduledDate;
  int id;
  String description;

  NamedNotification(this.scheduledDate, this.id, this.title, this.description);
}

I use this class to keep track of my notifications and add them to a list whenever a new notification is created. I do this like this:

List<NamedNotification> notifications;

onPressed: () {
    setState(() {
        NotificationPlugin newNotification = NotificationPlugin(); 
        newNotification.showAtDayAndTimeNotification(_dateTime, id, title, description);
        NamedNotification listNotification = NamedNotification(_dateTime, id, title, description);
        print(listNotification);
        notifications.add(listNotification);
        id++;
    });
    print(id);
    Navigator.pop(context);
},

However, whenever I try to add my namedNotification to the list, I get this error:

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

I was wondering what the best way was to fix this.

Upvotes: 3

Views: 5437

Answers (1)

chunhunghan
chunhunghan

Reputation: 54367

You forgot to init notifications
Please init notifications like this

List<NamedNotification> notifications = [];

Upvotes: 10

Related Questions