Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

flutter, iterate over documents in fire base collection

I’m trying to fetch all documents in a collection and iterate over them like so:

class InitialRecipe extends StatelessWidget {
  final UID;
  CollectionReference collection =
      FirebaseFirestore.instance.collection("recipes");

  InitialRecipe(this.UID, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return FutureBuilder<QuerySnapshot>(
      future: collection.get(), //.doc('VRWodus2pN2wXXHSz8JH').get(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        snapshot.data!.docs.forEach((e) {
          print(e.data.toString());
          print(e.data.runtimeType);
        });

        return Loading();
      },
    );
  }
}

and I cant get the documents. instead i get a message that tells me that the return value of snapshot.data is null.
error

I can however get a spesific document from the collection like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

FirebaseFirestore.instance.collection("recipes").doc('VRWodus2pN2wXXHSz8JH').get()

am I doing something wrong?

how can I iterate over the documents in the "recipes" collection??

>Solution :

It looks like your AsyncSnapshot hasn’t completed loading yet.

return FutureBuilder<QuerySnapshot>(
  future: collection.get(), //.doc('VRWodus2pN2wXXHSz8JH').get(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.hasError) {
      return Text("Something went wrong");
    }

    if (snapshot.hasData) { // 👈
      snapshot.data!.docs.forEach((e) {
        print(e.data.toString());
        print(e.data.runtimeType);
      });
    }

    return Loading();
  },
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading