Home > OS >  flutter local notification on firestore change
flutter local notification on firestore change

Time:11-15

In my firestore I have a list of documents which represent locations on a map.

I would like to show a local notification not only when a new document is created in the database, but also when the location is within a certain distance from my current location.

At the moment I have a streambuilder which loads the position into my local map, and a streamlistener to give a notification on a new document:

  CollectionReference loc =
      FirebaseFirestore.instance.collection('locations');
  late Stream<QuerySnapshot> _locStream;
  late StreamSubscription<QuerySnapshot> streamSub;

  @override
  void initState() {
    super.initState();
    _locStream = loc.snapshots();

    streamSub = _locStream.listen((data) {
      final snackBar = SnackBar(
          content:
              Text('New location added!'));

      ScaffoldMessenger.of(context).showSnackBar(snackBar);

    });
  }

the problem is that the stream is returning ALL the documents, not only the new one, so I have no idea how to "isolate" the new one and, more important, how to get its value in order to compare it with my current location.

Is that possible to achieve so?

CodePudding user response:

A Firestore QuerySnapshot always contains all information that fits within the query. But when the QuerySnapshot is an update on an existing listener/stream, it also contains metadata about what changes compared to the previous QuerySnapshot on the listener/stream.

To get access to this metadata, use the QuerySnapshot's docChanges property, rather than docs, and check the DocumentChangeType of the type property of each change to find only the documents that were added. In the initial snapshot that will be all of the documents, since all of them are new to the snapshot at that point.

See the Firebase documentation on viewing changes between snapshots

  • Related