'Flutter How To Update/Add Value to a Key in a Map<K,V>

Currently I have a map that looks like this to send emails via an API:

Map body = {"personalizations": [
    {
      "to": [
        {
          "email": "$receiverEmail"
        }
      ],
      "dynamic_template_data": {
        "EmployeeName": "$employeeName",
        "EmployeeID": "$employeeID",
        "PatientName": "$patientName",
        "ProviderName": "$providerName",
        "TreatmentDate": "$treatmentDate",
        "Diagnosis": "$diagnosis"
      }
    }
  ],
  "from": {
    "email": "$userEmail"
  },
  "template_id": "$templateID"
};

I am planning to use this structure with 2 forms of emails and for that to happen I need to update/add values under the dynamic_template_data key.

Therefore I am trying to find out how I could update/add value to that specific key. I found a function called Map.update() but I am unsure as how to properly use it. How do I approach this problem?



Solution 1:[1]

Just assign a new value to a specific key to update.

body['personalizations'][0]['dynamic_template_data']['EmployeeName'] = 'John Doe';

or

body['personalizations'][0]['dynamic_template_data']['Salary'] = 5000.00;

another example to do an assignment only if it doesn't exist yet

(body['personalizations'][0] as Map).putIfAbsent('Salary', () => 5000.00);

Solution 2:[2]

Map.update() and Map.updateAll() is a predefined function for this.

Map<String, bool> filterMap = {
    'All': true,
    'Open': false,
    'Inprocess': false,
    'Resolved': false,
    'Closed': false,
  };

just use this to set all value pairs to false :- filterMap.updateAll((key, value) => value = false);

OUTPUT :

[MapEntry(All: false), MapEntry(Open: false), MapEntry(Inprocess: false), MapEntry(Resolved: false), MapEntry(Closed: false)]

In case you want to change a single value :-

filterMap.update(filterMap.keys.toList()[index]),(value) => value = true);

(filterMap.keys.toList()[index]) -> this is key name. I have used it in list. So, to find a element on which user tapped, I have used this. You can give a key name there.

filterMap.update('Open'),(value) => value = true);

OUTPUT :

 [MapEntry(All: false), MapEntry(Open: true), MapEntry(Inprocess: false), MapEntry(Resolved: false), MapEntry(Closed: false)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Günter Zöchbauer
Solution 2 Yeasin Sheikh