Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Stream Building with a specific Firestore document

I am building a Flutter application and I am having trouble understanding how to implement Firestore. Out of the tutorials I have seen, I only see how to create a snapshot of an entire collection, however in my case, my collection is users, so I only need to snapshot the document of a particular user. There doesn't appear to be documentation on the Firebase docs on how to do this nor is there much documentation on the FlutterFire GitHub page. Please help!

This is the Widget I'm trying to build with StreamBuilder.

  @override
  Widget build(BuildContext context) {
    return new StreamBuilder(
      stream: Firestore.instance.collection('users').document(userId).snapshots(),
      builder: (context, snapshot) {
        return new ListView.builder(
          itemCount: //what do I put here?,
          itemBuilder: (context, index) => new Item(//And here?),
        );
      }
    );
  }
like image 680
Cole Weinman Avatar asked Jun 10 '18 22:06

Cole Weinman


2 Answers

Each element should be casted to have a reference later in the code.

  return new StreamBuilder<DocumentSnapshot>(
      stream: Firestore.instance.collection('users').document(userId).snapshots(), //returns a Stream<DocumentSnapshot>
      builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (!snapshot.hasData) {
          return new Text("Loading");
        }
        var userDocument = snapshot.data;
        return new Text(userDocument["name"]);
      }
  );
}
like image 67
Pedro Donoso Avatar answered Oct 17 '22 21:10

Pedro Donoso


Lets say you want to create a Text with the name parameter from your document

Widget build(BuildContext context) {
  String userId = "skdjfkasjdkfja";
  return StreamBuilder(
      stream: Firestore.instance.collection('users').document(userId).snapshots(),
      builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (!snapshot.hasData) {
          return Text("Loading");
        }
        var userDocument = snapshot.data;
        return Text(userDocument["name"]);
      }
  );
}

This is just one instance. Creating a StreamBuilder on the document will rebuild itself every time the document itself is changed. You can try this code, and then go to your console and change the "name" value. Your app will automatically reflect the changes.

Instead of just one Text, you could build entire tree that uses data from your stream.

If you want to get just at the moment value of the document, you can do so by resolving the Future of get() method on document reference.

var document = await Firestore.instance.collection('users').document(userId).get(),
like image 27
Tree Avatar answered Oct 17 '22 21:10

Tree