faccio
faccio

Reputation: 1014

How to iterate through fields in a Firestore Document in Flutter?

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

Upvotes: 1

Views: 466

Answers (2)

faccio
faccio

Reputation: 1014

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
                                      }

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317322

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

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

Upvotes: 1

Related Questions