Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset Firebase listeners in Flutter

I am creating a Flutter app that allows a user to have multiple accounts. When the user logout via the app it will bring them to a login screen which they can login to another account. The issue i am seeing is the firebase is pulling in the new account data and merging it with the previous account data. I am assuming that the listeners were not disconnected which cause the issue. How do I reset the Firebase listeners similar to the user opening the app? Below is an example of my listener I have. Thanks for any help or suggestions.

FirebaseDatabase.instance
        .reference()
        .child("accounts")
          ..onChildAdded
              .listen((event) => OnAddedAction(event)))
          ..onChildChanged
              .listen((event) => OnChangedAction(event)))
          ..onChildRemoved
              .listen((event) => OnRemovedAction(event))))); 
like image 919
Edmand Looi Avatar asked Dec 17 '22 23:12

Edmand Looi


1 Answers

You need to store the subscriptions and call cancel() on them:

var ref = FirebaseDatabase
            .instance
            .reference()
            .child("accounts");

var sub1 = ref.onChildAdded
              .listen((event) => OnAddedAction(event));
var sub2 = ref..onChildChanged
              .listen((event) => OnChangedAction(event))
var sub3 = ref.onChildRemoved
              .listen((event) => OnRemovedAction(event)); 

...

@override
dispose() {
  sub1?.cancel();
  sub2?.cancel();
  sub3?.cancel();
  super.dispose();
}
like image 78
Günter Zöchbauer Avatar answered Jan 02 '23 03:01

Günter Zöchbauer