TortillaPack
TortillaPack

Reputation: 225

How to get a specific Firestore document with a StreamBuilder

This is the setup of what I am currently using:

class BookList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('books').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError)
          return new Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting: return new Text('Loading...');
          default:
            return new ListView(
              children: snapshot.data.documents.map((DocumentSnapshot document) {
                return new ListTile(
                  title: new Text(document['title']),
                  subtitle: new Text(document['author']),
                );
              }).toList(),
            );
        }
      },
    );
  }
}

When I want to get a specific document, I read saw this example:

Firestore.instance
        .collection('talks')
        .document('document-name')
        .get()
        .then((DocumentSnapshot ds) {
      // use ds as a snapshot
    });

The problem is that I dont know how to use that example with my Streambuilder. When I tried this:

...

body: StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance
        .collection('talks')
        .document('document-name')
        .get()
        .then((DocumentSnapshot ds) {
      // use ds as a snapshot
    }),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.data == null)
            return Center(child: CircularProgressIndicator());
          if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
          if (snapshot.data.documents.length == 0)
...

I got:

The argument type 'Future' can't be assigned to the parameter type 'Stream'.dart(argument_type_not_assignable)

Upvotes: 0

Views: 1914

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599551

In the Flutter library for Firestore you can get a stream of a single document by calling the DocumentReference.snapshots() method.

So something like:

stream: Firestore.instance.collection('books').document('document-name').snapshots(),

Upvotes: 3

Related Questions