Home > Software design >  How to iterate through fields in a Firestore Document in Flutter?
How to iterate through fields in a Firestore Document in Flutter?

Time:08-27

I have a Firestore Document and I would like to iterate through them. I'm trying the following code, after looking in this question How to iterate through all fields in a firebase document?


FutureBuilder(
                                  future:   FirebaseFirestore.instance.collection('collection').doc('doc').get();,
                                  builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot){
                                    if (snapshot.hasData) {
                                      

                                      
                                      Map<String, dynamic> data = snapshot.data! as Map<String, dynamic>;
                                      



                                      for (var entry in data.keys) {
                                        // actions
                                      }

                                      

                                  }

                              ),

This code results in type '_JsonDocumentSnapshot' is not a subtype of type 'Map<String, dynamic>' in type cast

CodePudding user response:

data is a method, not a property on DocumentSnapshot. Call it using parenthesis:

Map<String, dynamic> data = snapshot.data() as Map<String, dynamic>;

CodePudding user response:

Finally I found the solution:

FutureBuilder(
                  future:   FirebaseFirestore.instance.collection('collection').doc('doc').get();,
                                  builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot){
                     if (snapshot.hasData) {
                                      
          Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;


                                      for (var match in data.keys) {
                                       // actions
                                      }
  • Related