【发布时间】:2021-08-25 15:27:44
【问题描述】:
我用 Firebase Cloud Notifications 编写了一个 Flutter 应用程序,它运行良好。但我正在努力让它以我想要的方式处理多个背景消息
场景:
- 我的应用程序在后台,两条消息到达。这些在 Android 通知区域中可见
- 点击一条消息,onMessageOpenedApp 将被调用,我已编写代码将用户带到应用程序的通知页面,其中列出了到达的通知。
- 因为我在 onMessageOpendApp 的通知列表中添加消息,所以我看不到第二条消息
- 我正在将通知添加到 onMessageOpenedApp 的列表中,因为我正在使用 Provider 更新需要“上下文”的通知列表
- 我觉得我必须将消息添加到为 onBackgroundMessage 定义的处理程序内的通知中,但如果这样做,我将无法使用“上下文”。
我觉得我搞错了。你能告诉我应该怎么做吗?
我在下面显示了我的应用程序中的代码 sn-ps。
//Handler to handle backgrount FCM messages - As a first level method
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print("Handling a background message: ${message.messageId}");
}
.
.
.
//Register the background messaging handler
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
.
.
.
// For handling notification when the app is in background but not terminated
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Message received while background ${message.notification.title}');
//Add the new notification to the list
PushNotification newBgNotification = PushNotification(
body: message.notification.body,
title: message.notification.title,
imageURL: message.notification.android.imageUrl,
);
Provider.of<FCMService>(context, listen: false).addNewNotification(newBgNotification);
print('-----------------Background Message aded to notification list');
Navigator.pushNamed(context, '/notifications');
});
【问题讨论】:
-
也许可以将传入消息的详细信息添加到特定的静态列表中,或者在它们到达后立即通过共享首选项保存它们,这样即使有超过 1 条通知,您也可以获得所有通知的详细信息。
-
@Darshan 考虑过使用共享首选项,但使用它是否是一个好习惯。状态似乎分散在其中,例如,当我点击第一条消息时,我可以从共享首选项中获取消息并填充通知列表。当我点击第二条消息时我应该怎么做。我必须检查 messageId 或类似的东西,如果尚未添加,我必须添加它们......感觉就像猴子修补......
-
另一方面,SharedPrefs 用于简单的键值对,消息结构很难在其中维护
-
您序列化和反序列化对象并将它们转换为字符串列表然后添加到共享首选项或尝试使用 sqflite。
标签: flutter firebase-cloud-messaging