Flutter and FCM send repeated notifications (android)

Viewed 143

In my chat app, I store the messages in a firestore document, so I use FCM only for notifying the user about new messages in the document. I have all the chat partecipants tokens stored in a field and with a for loop I send a message to all of them.

                   for (var d in widget.currMatch.deviceTokens) {
                      
                      if (d != thisDeviceToken) // I don't send the notification to this device
                        Api().sendFcm(
                            'New Message',
                            'you have a new message in your chat',
                            d);
                    }

if the app is closed no problem at all, I receive the notification in the system tray and it's ok.

But in case of the app is open, I receive the notification repeated sometimes 3 times sometimes 5 (it seems random but who knows). I use a snackbar to show the notification, so I see that appearing and disappearing for 3-5 times.

This problem doesn't occur on the android emulator, but only on phisical devices.

this is the code for the receiver part

_listener = FirebaseMessaging.onMessage.listen((RemoteMessage event) {
      print("message received");
      print(event.notification.body);

      // fa vedere una snackbar quando arriva un nuovo messaggio da FCM
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(event.notification.body),
          duration: const Duration(seconds: 2),
          action: SnackBarAction(
            label: 'OK',
            onPressed: () {},
          ),
        ),
      );

Why is that?

0 Answers
Related