Home > Software design >  How Can I Get Document name from AsyncSnapshot<QuerySnapshot>
How Can I Get Document name from AsyncSnapshot<QuerySnapshot>

Time:11-03

The Goal

Get a document name from AsyncSnapshot<QuerySnapshot>

What I Did

In this collection users there is many documents which name is uid. Using FutureBuilder and got AsyncSnapshot<QuerySnapshot>.

              FutureBuilder(
                future: FirebaseFirestore.instance
                    .collection("users")
                    .where('type', arrayContainsAny: ["Game", "Movie"])
                    .get(),
                builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                  if (snapshot.hasError) {
                    return Text(snapshot.error.toString());
                  }

                  if (snapshot.connectionState == ConnectionState.done) {
                    String uid = ...... // Want to get document id (= uid)

By using this snapshot, it was possible to get fields of each documents. But ofcourse these don't include their own name.

How can I get document id from AsyncSnapshot<QuerySnapshot>?

CodePudding user response:

snapshot.data!.docs can contain zero, 1 or more documents matching the criteria. This is a list of document snapshots.

So for example the first result can be in snapshot.data!docs[0]. From here to get the document id (in your case uid) simply use snapshot.data!docs[0].id.

  • Related