Unhandled Exception: NoSuchMethodError: The method 'showNotificationDaily' was called on null in flutter

Unhandled Exception: NoSuchMethodError: The method 'showNotificationDaily' was called on null in flutter

我正在尝试实现本地通知,但我遇到了 NoSuchMethodError,我调试了代码并找到了问题,但没有找到正确的解决方案. 我创建了通知管理器 class 我在 AddNotification.dart Stateful class

中这样称呼它
 final NotificationManager manager;
  const AddNotification(this.manager);

然后在它的状态中这样称呼它 class:

widget.manager.showNotificationDaily(1, "Asar", "isNotification", hour, minute);

在之前的 class 调用 AddNotification 的地方,我发送了一个这样的通知管理器对象。

class AllSurah extends StatefulWidget {
  NotificationManager manager;
  @override
  _AllSurahState createState() => _AllSurahState();
}
    Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => AddNotification(widget.manager)),
                  );

我已经调试了代码,发现管理器正在从之前 class 传递 NotificationManger 对象的地方传递 null。我该如何解决这个问题?

问题不在于您没有将变量传递给对象。相反,问题是 manager 变量在您调用 showNotificationDaily 时为空,这会引发您看到的异常。

您可以通过使用 Null Aware Operator?)来避免 Null 异常,像这样:

widget.manager?.showNotificationDaily(1, "Asar", "isNotification", hour, minute);

但这只会避免抛出 Exception。你真的应该调查为什么这个变量被传递为 null

试试下面的代码:

 NotificationManager manager = new NotificationManager();