Reputation: 250
When I get several documents from a collection, the result is only an array with each doc data.
firestore.collection("categories").valueChanges().subscribe(data => {
console.log(data);
// result will be: [{…}, {…}, {…}]
};
How can I get the name of each doc?
The ideal result would look like this:
{"docname1": {…}, "docname2": {…}, "docname3": {…}}
Upvotes: 8
Views: 31021
Reputation: 7
This is dart code:
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('your collection')
.snapshots(), // path to collection of documents that is listened to as a stream
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
return ListView(
children: snapshot.data.docs.map((DocumentSnapshot doc) { // get document data
return yourWidget( // return a widget for every document in the collection
docId: doc.id // get document name
);
}).toList(), // casts to list for passing to children parameter
);
},
),
Upvotes: 1
Reputation: 613
// Print each document
db.collection("categories")
.onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.data()); // For data inside doc
console.log(doc.id); // For doc name
}
}
Upvotes: 16
Reputation: 472
When you need to access additional metadata like the key of your Document, you can use the snapshotChanges()
streaming method.
firestore.collection("categories").valueChanges().map(document => {
return document(a => {
const data = a.payload.doc.data();//Here is your content
const id = a.payload.doc.id;//Here is the key of your document
return { id, ...data };
});
You can review the documentation for further explanation and example
Upvotes: 7