How do i store notifications received from Firebase Cloud messaging in StreamBuilder Widget?

50 Views Asked by At
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}'),
          ],
        ),
      );

I want to store all the notifications in notifications page from flutter cloud messaging, but I am only able to get one message at a time.

1

There are 1 best solutions below

0
On

The FirebaseMessaging.onMessage stream fires an event when a new message arrives. It does not keep a record of the messages that have arrived, or as they arrive.

So what you see is the expected behavior. If you want to have a list of all messages that have been received, you will have to create and maintain that yourself - for example by storing the messages in shared storage from an onMessage listener.


That is a good way to keep a persistent record of the messages that the app/device received. But since FCM does not guarantee message delivery, it does not ensure that your app has a record of all messages that the server has sent to it.

That's why for example in a chat app both of these will happen:

  1. The server sends you a message through FCM when something interesting happen.
  2. The app also retrieves all relevant messages from the server/database when it starts.

These two operations ensure the app has both the complete data, and that it gets the data while the app is not being used so that you can show a notification to the user.