Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I listen to a single document in Firestore with a StreamBuilder?

I'm trying to listen to changes in a single document of a collection, but I can't get it to work.

Widget build(BuildContext context) {
  return StreamBuilder(
    stream: Firestore.instance.collection("events").document(widget.documentID).get().asStream(),
    ...
  }
}

I'm using the .asStream() method, but I'm only getting the document once. If I change the data in the Firebase console, nothing updates unless I reopen the view.

Is there a way to do this?

like image 642
Nauzet Avatar asked Jun 08 '19 18:06

Nauzet


1 Answers

The reason you are only getting the document once is because the DocumentReference.get method originally only returns a Future and using asStream will only return that one single Future to the Stream.

The cloud_firestore package, however, has a built-in method of listening to documents properly.
You can use DocumentReference.snapshots instead, which returns a Stream of every change of that document.

In your code, you will only have to replace .get().asStream() by .snapshots().

like image 172
creativecreatorormaybenot Avatar answered Nov 15 '22 19:11

creativecreatorormaybenot