Udit Chugh
Udit Chugh

Reputation: 711

How can I add an element to each Map in a List of Maps?

I am storing each Firestore document's data into a list, but I also want to store the document ID with that data.

List<DocumentSnapshot> documentSnapshotsList =
                    querySnapshot.data.documents;

//Convert document snapshots list into a list of variations
List<Map> variationsData = documentSnapshotsList
                        .map((element) => element.data)
                        .toList();

But I don't know how to edit each element in a List<Map>. I do understand that the document ID is accessible via DocumentSnapshot.

Please feel free to share a better approach if you have one in mind.

Upvotes: 0

Views: 170

Answers (2)

Raj Yadav
Raj Yadav

Reputation: 10768

That's pretty simple,

List<Map> variationsData = documentSnapshotsList
    .map((element) => {
        "id": element.id, 
        "key1": element.data["key1"], //customize your map accordingly
    }).toList();

Upvotes: 0

Udit Chugh
Udit Chugh

Reputation: 711

I was able to do it using the below code:

List < DocumentSnapshot > documentSnapshotsList =
    querySnapshot.data.documents;

//Convert document snapshots list into a list of variations
List < Map > variationsData =
    documentSnapshotsList.map((element) {
        Map tempMap = element.data;
        tempMap['variationDocumentId'] = element.documentID;
        return tempMap;
    }).toList();

Upvotes: 1

Related Questions