在我的Flutter应用程序中,StreamSubscription
没有暂停或取消。当我调用cancel()
时,如果它以前启动过,它将停止。如果我在启动后调用cancel()
,它不会停止。我正在使用Firestore快照侦听器。下面是我的代码。我尝试了不同的方法,但仍然不起作用。问题是Firestore listener
在加载数据后没有停止。
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();
}
发布于 2019-02-27 16:33:00
当您推送新页面时,上一页仍会呈现,因此不会调用dispose()
。
此外,有时可能会发生小部件不再呈现但dispose
尚未调用的情况,这可能会导致奇怪的错误消息。因此,如果您使用dispose
,添加这样的检查可能也是一个好主意。
变化
//It will display items
至
if(myIsCurrentRoute && mounted) {
//It will display items
}
发布于 2019-02-27 16:34:32
您没有将订阅赋值给正确的变量。
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();
}
发布于 2019-10-15 20:55:47
我也遇到过同样的问题,结果发现在取消之前,流似乎一直在监听事件,但是如果你进行调试,你会发现在调用dispose之后,它会在某个时刻停止监听。因此,Gunter's解决方案工作得很好,因为如果mount为false,您可以防止调用回调函数,这意味着您的页面不再存在。
https://stackoverflow.com/questions/54899927
复制相似问题