FlutterFire Messaging:您的后台消息处理程序发生错误

FlutterFire Messaging: An error occurred in your background messaging handler

我正在使用 firebase 消息传递和 flutter hive 包,我正在制作一个聊天应用程序并将收到的消息保存到 hive 中,这样聊天也可以离线进行。 当收到通知并且应用程序关闭时,我正在使用 firebase 消息传递 onBackgroundMessage 处理程序我这样做是为了将消息数据存储在配置单元中,而应用程序不是 运行:

Future<void> _firebaseMessagingBackgroundHandler(
    final RemoteMessage message) async {
  if (message.data["Type"] == "ChatMessage") {
    //*******WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    final DocumentSnapshot documentSnapshot =
        await ChatFirestore.getDocumentSnapshot(
            collectionName: "Messages", documentId: message.data["MessageId"]);
    if (documentSnapshot != null && documentSnapshot.exists) {
      final MessageModel newMessage = MessageModel.fromMap(
          map: documentSnapshot.data(),
          fromMe: ChatHelpers.isReceivedMessageFromMe(
              otherChatUserId: message.data["SenderId"]),
          status: 2,
          receiptDeviceTimestamp: DateTime.now().millisecondsSinceEpoch,
          deleted: false);
      await ChatHive.saveMessageFromNotification(message: newMessage);
      await ChatHelpers.updateAppBadge(inForeground: false);
      await ChatFirestore.modifyDocumentSnapshot(
        collectionName: "Messages",
        documentId: newMessage.id,
        newInformation: {
          "Status": 2,
          "ReceiptDeviceTimestamp": newMessage.receiptDeviceTimestamp,
        },
      );
    }
  }
}

但我总是在日志中收到此错误:

I/flutter (13090): FlutterFire Messaging: An error occurred in your background messaging handler:
I/flutter (13090): NoSuchMethodError: The getter 'id' was called on null.
I/flutter (13090): Receiver: null
I/flutter (13090): Tried calling: id

这是我的 saveMessageFromNotification 函数:

await Hive.initFlutter();
if (!Hive.isAdapterRegistered(6)) {
   Hive.registerAdapter<MessageModel>(MessageModelAdapter());
}
final Box<MessageModel> messagesBox =
    await Hive.openBox<MessageModel>("MessagesBox");
messagesBox.put(message.id, message);

这是我的 flutter doctor 结果:

[✓] Flutter (Channel stable, 2.2.3, on macOS 11.4 20F71 darwin-x64, locale
    en-SA)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.58.2)
[✓] Connected device (4 available)

• No issues found!

将其包装在 IF 语句中,以检查消息是否不为空。

if(newMessage!=null) await ChatFirestore.modifyDocumentSnapshot(
        collectionName: "Messages",
        documentId: newMessage.id,
        newInformation: {
          "Status": 2,
          "ReceiptDeviceTimestamp": newMessage.receiptDeviceTimestamp,
        },
      );