0
votes

I am using dart to query my collection in firestore in order to get a list of strings. Here's the firestore structure:

FireStore List

Here's my code:

  Future getIngredients() async {
        var firestore = Firestore.instance;
        List<String> ingredients = new List<String>();
        // this will return exactly one document every time. 
        CollectionReference col = firestore.collection("ingredients");
        Query query = col.where('name', isEqualTo: widget.dish_name.toString().toLowerCase());
    // How do I retrieve the ingredient list?
} 

Any ideas?

Update

Here's what I did after following this link.

Future getIngredients() async {

    var list = [];
    Firestore.instance
        .collection('ingredients')
        .where("name", isEqualTo: widget.dish_name.toString().toLowerCase())
        .snapshots()
        .listen((data) =>
        data.documents.forEach((doc) => list.add(doc["ingredients"])));

       print("First item is" + list[0]);
     return list;
  }

However, the list seems to be empty. However, when I do print(doc["ingredients"]), I get all the data. What am I doing wrong?

Second Update

So I managed to get the data and now I am trying to display it with the following code:

new ListView.builder(
                  itemExtent: 90,
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {

                      return SingleIngredient(
                        ingredient_name: snapshot.data[index].data["ingredients"],

                      );


                  });

However I am getting the following error:

Class 'QuerySnapshot' has no instance getter 'length'. I/flutter (31722): Receiver: Instance of 'QuerySnapshot' I/flutter (31722): Tried calling: length

Any ideas how to iterate through the ingredient list?

1
Please refer the example given here. - yashthakkar1173
Please see my update - bangbang
doc["ingredients"] will return list. And you are trying to add that list to first item of your list. That's why it's not working! - yashthakkar1173
How do I return a list then? What confuses me is the foreach syntax. That's why I though I had to add each item to my list - bangbang
It's already given here under Binding a CollectionReference to a ListView section. - yashthakkar1173

1 Answers

0
votes

It's likely that you forgot to call setState after updating the List in the class.

Future getIngredients() async {
  var list = [];
  FirebaseFirestore.instance
      .collection('ingredients')
      .where("name", isEqualTo: widget.dish_name.toString().toLowerCase())
      .get()
      .then((data) =>
          data.docs.forEach((doc) {
            setState(() {
              list.add(doc['ingredients']);
            });
          }));
}