在我扑朔迷离的应用程序中,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();
}
答案 0 :(得分:1)
我遇到了同样的问题,事实证明,在取消之前,流似乎一直在监听事件一段时间,但是如果进行调试,您会看到在调用dispose之后它将停止监听。 因此,Gunter's解决方案效果很好,因为如果mount为false,则可以防止调用回调函数,这意味着您的页面不再在那里。
答案 1 :(得分:0)
当您推送新页面时,仍会呈现上一页,因此不会调用dispose()
。
有时也可能会发生这样的情况,即不再渲染窗口小部件,但尚未调用dispose
,这可能会导致奇怪的错误消息。因此,如果使用dispose
,那么添加这样的检查也是一个好主意。
更改
//It will display items
到
if(myIsCurrentRoute && mounted) {
//It will display items
}
答案 2 :(得分:0)
您没有将订阅分配到正确的变量中。
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();
}