How to trigger a Future method when a new document in Firestore is created. Flutter

Viewed 125

I have a Future which call a Ringtone with this dependency

Future<void> getRing()async {
FlutterRingTonePlayer.playAlarm();
}

I want to trigger the method getRing when a new document is created into my collection and add a new item in the list. How I can achieve that without creating a firebase function?

2 Answers

You can listen for stream see the documentation for more info

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

You can read data from Firestore in realtime using streams and track changes to collection with QuerySnapshot's docChanges property.

Just subscribe to collection using .snapshots(), inspect document changes in received QuerySnapshot and trigger your Future if there is a new doc.

Related