Stop listening to snapshot updates in cloud firestore in flutter
The listen
method returns a Subscription
This class is used to cancel the listening.
You should store inside your state that object to cancel subscription on dispose.
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();
Very late answer, but I thought I'd complete the previous answers with a code sample as it might be useful to others.
class EventsScreen extends StatefulWidget {
EventsScreen({Key key}) : super(key: key);
@override
_EventsScreenState createState() => _EventsScreenState();
}
class _EventsScreenState extends State<EventsScreen> {
StreamSubscription<QuerySnapshot> _eventsSubscription;
@override
void initState() {
// Initialise your stream subscription once
CollectionReference eventsReference = Firestore.instance.collection('Events');
_eventsSubscription = eventsReference.snapshots().listen((snapshot) => _onEventsSnapshot);
super.initState();
}
@override
Widget build(BuildContext context) {
// Build your widget here
return Container();
}
void _onEventsSnapshot(QuerySnapshot snapshot) {
// Remove the setState() call if you don't want to refresh your screen whenever you get a fresh snapshot
setState(() {
snapshot?.documentChanges?.forEach(
(docChange) => {
// If you need to do something for each document change, do it here.
},
);
// Anything you might do every time you get a fresh snapshot can be done here.
});
}
@override
void dispose() {
// Cancel your subscription when the screen is disposed
_eventsSubscription?.cancel();
super.dispose();
}
}
This approach leverages the StatefulWidget's state to handle documents changes.
A better approach would be to use a Provider or the BLoC pattern so that the subscription to your Firestore is not created and handled in the UI.