Learn
Learn

Reputation: 59

How to display a Map inside a field of a specific document in firestore using flutter?

This is the structure Hello, how to retrieve a map from firestore which is inside a field of a specific document and how to display it as a list in the app. How can be this achieved? Can someone please share a example snippet of code. Like for example in "Collection-Doc-Field-{key : value}" i want to display the map which is in the Field.

Updated :

Expanded(
                child: new ListView(
                  children: snapshot.data
                      .get('$field')
                      .map((DocumentSnapshot document) {
                    return new ListTile(
                        title: Column(
                            children: (document.data()['$field']
                                    as Map<String, dynamic>)
                                .entries
                                .map((e) => ListTile(
                                    title: Text(e.key),
                                    trailing: Text(e.value.toString())))
                                .toList())
                        //subtitle: new Text(document.data()['Subjects']),
                        );
                  }).toList(),
                ),
              ),

This is how im trying to display the Map of field, but ending up with this error

The following _TypeError was thrown building StreamBuilder<DocumentSnapshot>(dirty, state: _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot<DocumentSnapshot>>#d3cf2):
type '(DocumentSnapshot) => ListTile' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'

Upvotes: 0

Views: 1015

Answers (1)

Victor Eronmosele
Victor Eronmosele

Reputation: 7686

In your code, snapshot.data is a DocumentSnapshot object. So, when you call .get(field), it returns a Map<String, dynamic> object based on your database structure. When you write .map(DocumentSnapshot document), you're using the wrong type as it is meant to map through the items in the Map<String, dynamic> which is not of type DocumentSnapshot.

Solution

You need to cast the result of your get('$field') [which can be simplified to get(field)] to the type of object you're expecting [in this case, it is of type Map<String, dynamic>] and then you loop through each map entry to return a ListTile widget.

Update your code to the one below and that should fix the error:

     return ListView(
       children:
         (snapshot.data.get(field) as Map<String, dynamic>)
           .entries
           .map((MapEntry mapEntry) {
             return ListTile(
               title: Text(mapEntry.key),
               trailing: Text(mapEntry.value.toString()));
       }).toList(),
     );

Upvotes: 2

Related Questions