Home > OS >  flutter, iterate over documents in fire base collection
flutter, iterate over documents in fire base collection

Time:12-30

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??

CodePudding user response:

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) { //            
  • Related