FlutterFire 消息:您的后台消息处理程序中发生错误
Posted
技术标签:
【中文标题】FlutterFire 消息:您的后台消息处理程序中发生错误【英文标题】:FlutterFire Messaging: An error occurred in your background messaging handler 【发布时间】:2021-10-07 14:50:27 【问题描述】:我正在使用 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 (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!
【问题讨论】:
【参考方案1】:将其包装在 IF 语句中,以检查消息是否不为空。
if(newMessage!=null) await ChatFirestore.modifyDocumentSnapshot(
collectionName: "Messages",
documentId: newMessage.id,
newInformation:
"Status": 2,
"ReceiptDeviceTimestamp": newMessage.receiptDeviceTimestamp,
,
);
【讨论】:
谢谢,问题已解决。问题是我从常量类中的静态变量获取聊天用户 ID,但是当应用程序在后台时,所有变量都变为空,所以我必须从配置单元获取它,注意你必须再次初始化配置单元并注册使用如果您希望 hive 在后台工作,请再次适配器。谢谢。以上是关于FlutterFire 消息:您的后台消息处理程序中发生错误的主要内容,如果未能解决你的问题,请参考以下文章