Flutter:在 null 上调用了方法“add”

flu*_*g98 3 list dart flutter

所以我创建了一个简单的通知类,如下所示:

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

  NamedNotification(this.scheduledDate, this.id, this.title, this.description);
}
Run Code Online (Sandbox Code Playgroud)

我使用这个类来跟踪我的通知,并在创建新通知时将它们添加到列表中。我这样做:

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);
},

Run Code Online (Sandbox Code Playgroud)

但是,每当我尝试将我的 namedNotification 添加到列表中时,我都会收到此错误:

The method 'add' was called on null.
Receiver: null
Tried calling: add(Instance of 'NamedNotification')
Run Code Online (Sandbox Code Playgroud)

我想知道解决这个问题的最佳方法是什么。

chu*_*han 10

你忘了初始化notifications
notifications像这样初始化

List<NamedNotification> notifications = [];
Run Code Online (Sandbox Code Playgroud)

  • add是属于List的方法。如果您在调用变量时没有初始化变量,则会产生错误,并且您将看到 The method 'abc' was called on null。始终检查实例 (2认同)