ad_on_is
ad_on_is

Reputation: 1550

Flutter FirebaseMessaging - StreamSubscription not handled properly

I have a the following basic example, which does not seem to work properly:

pubspec.yaml:

firebase_messaging: ^10.0.0

FcmService.dart

StreamSubscription fcmListener;

void init() {
   fcmListener = FirebaseMessaging.onMessage.listen((RemoteMessage message) {
     // do stuff
   });
}

void dispose() {
   print('SUBSCRIPTION canceled');
   fcmListener.cancel()
}

App.dart

void init() {
   fcmService.init();
   // other inits()
}

void dispose() {
   print('EVERYTHING disposed');
   fcmService.dispose();
   // other disposes()
}

Problem

After I log in into my app the init() method of App.dart is called, and everything is set up properly. The FCM service works all fine. When I log-out of the app the dispose() method of App.dart is called and the app redirects to Login.dart. The proper logs are EVERYTHING disposed and SUBSCRIPTION canceled.

However,if I log in again (without hot reloading the app) I get the following error message, regarding fcmListener = FirebaseMessaging.onMessage.listen()

Unhandled Exception: Bad state: Cannot add new events while doing an addStream. Although, the FCMService still works as expected.

This only happens in the new firebase_messaging, which they rewrote a while ago. I used this same code with a previous version of firebase_messaging, and this exception did not occur.

Am I missing something here?

Upvotes: 2

Views: 926

Answers (2)

farahis dev
farahis dev

Reputation: 1

you can use subscribe and topics feature in firebase cloud messaging. this is another easy way.

Login
FirebaseMessaging.instance.unsubscribeFromTopic("guest");
FirebaseMessaging.instance.subscribeToTopic("loggedIn");

Logout
FirebaseMessaging.instance.subscribeToTopic("guest");
FirebaseMessaging.instance.unsubscribeFromTopic("loggedIn");

FCM Api = 
{
 "to" : "/topics/loggedin",
 "notification" : {
     "title" : "your title notification",
     "body" : "your body notification"
 }
}

Upvotes: 0

BbL
BbL

Reputation: 76

Try to call .asBroadcastStream() after FirebaseMessaging.onMessage:

void init() {
  fcmListener = FirebaseMessaging
    .onMessage
    .asBroadcastStream()
    .listen((RemoteMessage message) {
      // do stuff
    });
}

The same method should be called with FirebaseMessaging.onMessageOpenedApp. I have found this solution in a GitHub issue.

Upvotes: 2

Related Questions