在Flutter中停止收听Cloud Firestore中的快照更新

时间:2018-08-19 13:18:49

标签: flutter google-cloud-firestore

我想停止收听快照更新。即使关闭屏幕,快照仍会继续监听更新。我正在使用下面的代码来监听更新。

CollectionReference reference = Firestore.instance.collection('Events');
reference.snapshots().listen((querySnapshot) {
  querySnapshot.documentChanges.forEach((change) {
    // Do something with change
  });
})

4 个答案:

答案 0 :(得分:7)

您的侦听器的类型为StreamSubscription,因此您可以在侦听器上调用一些有用的方法,例如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();

答案 1 :(得分:3)

listen方法返回一个Subscription

该类用于取消监听。

您应该在该状态内存储该对象以在处理时取消订阅。

答案 2 :(得分:2)

答案很晚,但是我想我会用一个代码示例完成以前的答案,因为它可能对其他人有用。

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();
  }
}

这种方法利用StatefulWidget的状态来处理文档更改。

一种更好的方法是使用ProviderBLoC pattern,以便不会在UI中创建和处理对Firestore的订阅。

答案 3 :(得分:0)

正确的方法是stream.pause() 所以听众将处于暂停模式 cancel() 销毁侦听器及其内容