[英]Flutter app global state frorm streamsubscription of firebase document
[英]Flutter StreamSubscription not stopping or pausing
在我的 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();
}
推送新页面时,仍会呈现上一页,因此不会调用dispose()
。
此外,有时可能会发生小部件不再呈现但尚未调用dispose
情况,这可能导致奇怪的错误消息。 因此,如果您使用dispose
添加这样的检查可能也是一个好主意。
改变
//It will display items
到
if(myIsCurrentRoute && mounted) {
//It will display items
}
您没有将订阅分配到正确的变量中。
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();
}
我遇到了同样的问题,结果流似乎在取消之前继续侦听事件一段时间,但是如果您进行调试,您会看到在调用 dispose 后它会在某个时候停止侦听。 因此, Gunter 的解决方案工作正常,因为如果 mount 为 false,您可以防止调用回调函数,这意味着您的页面不再存在。
我们还使用StreamSubscription
来监听文档更改。 这是 Firestore 提供的一项很棒的功能。 听力到底什么时候结束。
假设您从不主动取消它,它会继续听多久? 即使在应用程序关闭后?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.