Flutter StreamSubscription not stopping or pausing
Solution 1
When you push a new page, the previous page is still rendered and therefore dispose()
is not called.
Also sometimes it can happen that the widget is not rendered anymore but dispose
was not yet called, which can lead to weird error messages. So adding such a check is probably a good idea as well if you use dispose
.
Change
//It will display items
to
if(myIsCurrentRoute && mounted) {
//It will display items
}
Solution 2
You are not assigning the subscription into the right variable.
StreamSubscription<QuerySnapshot> subscription;
@override
void initState() {
super.initState();
print("Creating a streamSubscription...");
subscription=Firestore.collection("name").document("d1").collection("d1")
.snapshots().listen((data){
//It will display items
}, onDone: () { // Not excecuting
print("Task Done");
}, onError: (error) {
print("Some Error");
});
subscription.cancel(); //It will work but cancel stream before loading
}
@override
void dispose() {
subscription.cancel(); //Not working
super.dispose();
}
Solution 3
I was experiencing the same problem and it turns out that the stream seems to keep listening for events for a while before canceling, but if you debug you will see that after dispose is called it will stop listening at some point. Therefore, Gunter's solution works fine, since you can prevent your callback function from being called if mount is false, which means your page is no longer there.
Joe
Updated on December 09, 2022Comments
-
Joe over 1 year
In my Flutter app
StreamSubscription
is not pausing or cancelling. When I callcancel()
if it started before, it will stop. If I callcancel()
after starting, it will not stop. I am using Firestore snapshot listener. Below is my code. I have tried different methods but it's still not working. The problem is that the Firestorelistener
is not stopping after loading data.StreamSubscription<QuerySnapshot> streamSubscription; @override void initState() { super.initState(); print("Creating a streamSubscription..."); streamSubscription =Firestore.collection("name").document("d1").collection("d1") .snapshots().listen((data){ //It will display items }, onDone: () { // Not excecuting print("Task Done"); }, onError: (error) { print("Some Error"); }); streamSubscription.cancel(); //It will work but cancel stream before loading } @override void dispose() { streamSubscription.cancel(); //Not working super.dispose(); }