Bnd10706
Bnd10706

Reputation: 2373

Flutter and Cloud Firestore how to access 2nd level category list

I have a firebase database that is built like this.

MainCategories - Cat 1 - 
                        - SubCategories -
                                    - Sub Cat 1
                                    - Sub Cat 2
                 Cat 2 - SubCategories -
                                    - Sub Cat 1
                                    - Sub Cat 2
                                    - Sub Cat 3
                 Cat 3 - SubCategories -
                                    - Sub Cat 1
                 Cat 4 - SubCategories -
                                    - Sub Cat 1
                                    - Sub Cat 2
                                    - Sub Cat 3

I am trying to do a list builder on my homepage to to populate the Main Categories, I have managed to do this with

Query collectionReference = Firestore.instance.collection("mainCategories").orderBy("title");

Then I have a list view builder that is working fine for the main Categories

                      ListView.builder(
                      itemCount: snapshot.length,
                      itemBuilder: (context, index) {
                        return InkWell(
                          onTap: () => passData(snapshot[index]),
                          child: MainCard(
                            title: snapshot[index].data["title"],
                            subtitle: snapshot[index].data["subTitle"],
                            image: snapshot[index].data["image"],
                          ),
                        );
                      }),
                ),

Im passing the data with

passData(DocumentSnapshot snap) {
    Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => Category(snapshot: snap,)));
  }

Which I am not even sure if its needed.

IN the Category widget I am looking to build another list view of the sub categories

So in this case if they selected the 2nd category it should show you a list view of the 3 sub categories.

I am not sure if I am passing the data right to begin with and in the Category widget I am sure I am not querying it correctly.

Query collectionReference = Firestore.instance.collection("subCategories");

I am looking to see how to populate that 2nd level of categories in the listview builder

Upvotes: 0

Views: 1403

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317542

If your subcategories actually implemented as nested subcollections in Firestore, the query looks more like this:

Query subCategoriesQuery = Firestore.instance
    .collection("mainCategories")
    .document(cat)
    .collection(subCat)

You will need to provide a value for both cat as the name of the top level category document, and a value for subCat for the name of the subcategory subcollection.

Upvotes: 1

Related Questions