Stop listening to snapshot updates in cloud firestore in flutter

Issue

I want to stop listening to snapshot updates. The snapshot keeps listening to updates even after the screen is closed. I am using the below code to listen to the updates.

CollectionReference reference = Firestore.instance.collection('Events');
reference.snapshots().listen((querySnapshot) {
  querySnapshot.documentChanges.forEach((change) {
    // Do something with change
  });
})

Solution

Your listener is of type StreamSubscription, so you can call some helpful methods on your listener such as cancel()

    CollectionReference reference = Firestore.instance.collection('Events');
StreamSubscription<QuerySnapshot> streamSub = reference.snapshots().listen((querySnapshot) {
  querySnapshot.documentChanges.forEach((change) {
    // Do something with change
  });
});
//somewhere
streamSub.cancel();

Answered By – Shady Aziza

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *