Ciprian
Ciprian

Reputation: 3226

Get Firestore document key with Flutter

I've got the following code from https://pub.dartlang.org/packages/cloud_firestore#-readme-tab-, but I'm not sure how to get each document's key. What I want to do is tap on each term to view or got to an edit page.

Firestore data model:

-content
--sPuJxAJu0dBMZLBTakd4
---term
---body content

Code:

class _TermsState extends State<Terms> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('content').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');

        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Text('Loading...');
          default:
            return ListView(
              children:
                  snapshot.data.documents.map((DocumentSnapshot document) {
                print(document['term']);
                return ListTile(
                  title: Text(document['term']),
                );
              }).toList(),
            );
        }
      },
    );
  }
}

Upvotes: 5

Views: 3907

Answers (2)

pythonNovice
pythonNovice

Reputation: 1431

An update to the above answer from creativecreatorormaybenot, the document ID can now be found in document.id from DocumentSnapshot. document.documentID will not return the id.

Here's a link to the answer I found

Upvotes: 0

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126694

When you have a DocumentSnapshot, you can use document.documentID to get its key and document.reference.path to get the whole path.

In this case document is an object of type DocumentSnapshot, which you already retrieve correctly.

Upvotes: 5

Related Questions