How to reset Firebase listeners in Flutter

2019-04-14 20:11发布

问题:

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))))); 

回答1:

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.cnacel();
  super.dispose();
}