如何在 StreamBuilder Widget 中存储从 Firebase Cloud 消息传递收到的通知?

问题描述 投票:0回答:1
List<String> notifications = [];
StreamBuilder<RemoteMessage>(
  stream: FirebaseMessaging.onMessage,
  builder:
      (BuildContext context, AsyncSnapshot<RemoteMessage> snapshot) {
    if (snapshot.hasData) {
      List<String> messagesShow = [];
      RemoteMessage message = snapshot.data!;
      final messageText = message.notification?.title;
      final messageBody = message.notification?.body;
      for (var message in message.data) {} //this doesnt get called?

      _messageController.add('New Message');
      notifications.add(message.toString());
      return Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('${message.notification?.title}'),
            const SizedBox(
              height: 10.0,
            ),
            Text('${message.notification?.body}'),
          ],
        ),
      );

我想将flutter云消息通知页面中的所有通知存储起来,但我一次只能收到一条消息。

flutter listview firebase-cloud-messaging stream-builder
1个回答
0
投票

当新消息到达时,

FirebaseMessaging.onMessage
流会触发一个事件。它保留已到达或到达时的消息的记录。

所以你看到的是预期的行为。如果您想要拥有已收到的所有消息的列表,则必须自己创建和维护该列表 - 例如,通过将消息从

onMessage
侦听器存储在共享存储中。


这是持久记录应用程序/设备收到的消息的好方法。但由于 FCM 不保证消息传递,因此它不能确保您的应用程序拥有服务器发送给它的所有消息的记录。

这就是为什么在聊天应用程序中,这两种情况都会发生:

  1. 当发生有趣的事情时,服务器会通过 FCM 向您发送消息。
  2. 应用程序启动时还会从服务器/数据库检索所有相关消息。

这两个操作确保应用程序拥有完整的数据,并且在应用程序未使用时获取数据,以便您可以向用户显示通知。

© www.soinside.com 2019 - 2024. All rights reserved.