Kfir Ettinger
Kfir Ettinger

Reputation: 632

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:

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

am I doing something wrong?

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

Upvotes: 0

Views: 165

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600090

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();
  },
);

Upvotes: 2

Related Questions