Home > Enterprise >  How to access document fields using document id in Cloud FireStore?
How to access document fields using document id in Cloud FireStore?

Time:11-15

I have a

Querysnapshot snapshot

I can supply an index and access the fields of the document perfectly like:

snapshot.data!.docs[index]

However, I want to access the field of document 'thisParticularDocument' which is the id (name) of the document in Cloud Firestore.

I want to use

snapshot.data!.docs[thisParticularDocument] 

but that doesn't work because you can only supply an index to docs.

I want a solution that preferably involves no async await.

CodePudding user response:

you can get the data of a document with a specific id without making a new async request by finding it like this:

   snapshot.data!.docs.firstWhere((doc) => doc.id == "the document Id").data() as Map<String, dynamic>;

this will get you the specific document from the QuerySnapshot.

CodePudding user response:

when you a get a QuerySnapshot then you get all all documents of it including references and data.

so you can get a specific document as you say like this:

snapshot.data!.docs[index]

and you can get the data of document like this:

snapshot.data!.docs[index].data() as Map<String, dynamic>

then you can get the specific field inside of it like this:

(snapshot.data!.docs[index].data() as Map<String, dynamic>)["thisParticularDocument"]

that's it the value of that field will be returned fine if it exists.

  • Related