Search code examples
fluttergoogle-cloud-firestorestream

How do I listen to a Stream<QuerySnapshot> only for adds to a Firebase collection?


I have a collection of records on firestore and I want to play a sound when a new one is added. I have Hive installed on the project so I kept track of the last seen number of records and only play the sound of the new list is longer.

But is there a better way? Ideally a way to get only if my stream has a record added to it?

final Stream<QuerySnapshot> stream = FirebaseFirestore.instance
    .collection('myItems')
    .where(
      "date",
      isGreaterThanOrEqualTo:
          DateTime.now().add(const Duration(hours: -12)),
    )
    .snapshots();

stream.listen((event) async {
  if (event.docs.length > HiveService.getLastAmountOfRecordsSeen()) {
    final AudioPlayer player = AudioPlayer();
    final AssetSource audioasset = AssetSource('sound/beep.wav');

    await player.play(audioasset);
    MyHiveService.setLastAmountOfRecordsSeen(event.docs.length);
  }
});

Solution

  • You can use event.docChanges to detect changes in the listener, and there is also a way to determine the type of the change.

    Loop through the changes and check for the change type like this within the listener function:

    for (var change in event.docChanges) {
      if (change.type == DocumentChangeType.added) {
        // you can play the sound and break the loop here,
        // if you are interested only in whether any document
        // was added, but you can keep looping if you
        // need the total number of added documents
      }
    }
    

    See documentation for further details.