Home > Software engineering >  get all data from a firestore subcollection flutter
get all data from a firestore subcollection flutter

Time:09-11

I want to get all the data in a firestore subcollection.

This is how my firestore collection looks like:

firestore collection

The collection Products has a product with a field productName. I

I can display the list name by accesing the snapshot data

CloudShoppingListsCart.fromSnapshot(QueryDocumentSnapshot<Map<String, dynamic>> snapshot, this.products)
  : shoppingListId = snapshot.id,
    name = snapshot.data()['name'] as String;

but is there a way to access the collection products and his fields like I did in snapshot.data()?

The method where I call fromSnapshot is this:

Stream<Iterable<CloudShoppingListsCart>> getShoppingCartListDetails({required String shoppingCartListId}){

final shoppingList = FirebaseFirestore.instance.collection(shoppingListCollectionName)
    .doc(shoppingCartListId).collection(shoppingListCartCollectionName).snapshots().map((event) =>
    event.docs
        .map((doc) => CloudShoppingListsCart.fromSnapshot(doc, [])));

return shoppingList;

I want to get the product name for displaying it in a ListTile like this

return ListTile(
  leading: const Icon(Icons.list),
  trailing: const Text(
     "GFG",
     style: TextStyle(color: Colors.green, fontSize: 15),),

  title: Text('List item $productsName'));

I am already displaying the list name in a column.

Thanks in advance.

CodePudding user response:

As Peter commented: read operations on Firestore are shallow. A document snapshot from the parent collection, does not contain snapshots from its subcollections.

This means that you will have to execute an additional read operation to get the documents from the products subcollection.

  • Related