【问题标题】:Flutter: The method 'add' was called on nullFlutter:在 null 上调用了“add”方法
【发布时间】:2020-04-27 16:42:05
【问题描述】:

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

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

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

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

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

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

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

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

【问题讨论】:

    标签: list flutter dart


    【解决方案1】:

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

    List<NamedNotification> notifications = [];
    

    【讨论】:

    • 是的,这解决了问题。我很好奇,为什么会导致错误?
    • add是属于List的方法。如果你在调用它时没有初始化变量,它会产生错误,当你看到 The method 'abc' was called on null 时。总是检查实例
    • 很高兴为您提供帮助。如果对您有帮助,请将其标记为答案。谢谢。
    • 伙计,我开始感到失落。 +1
    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 2020-11-06
    • 2019-09-23
    • 2020-06-04
    • 2021-09-01
    • 1970-01-01
    相关资源
    最近更新 更多