Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: The method 'add' was called on null

Tags:

list

flutter

dart

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.

like image 303
flutterbug98 Avatar asked Feb 24 '26 19:02

flutterbug98


1 Answers

You forgot to init notifications
Please init notifications like this

List<NamedNotification> notifications = [];
like image 192
chunhunghan Avatar answered Feb 26 '26 10:02

chunhunghan