How to add a new pair to Map in Dart?

You can add a new pair to a Map in Dart by specifying a new key like this:

Map<String, int> map = {
  'a': 1,
  'b': 2,
};

map['c'] = 3;  // {a: 1, b: 2, c: 3}

According to the comments, the reason it didn't work for the OP was that this needs to be done inside a method, not at the top level.


To declare your map in Flutter you probably want final:

final Map<String, int> someMap = {
  "a": 1,
  "b": 2,
};

Then, your update should work:

someMap["c"] = 3;

Finally, the update function has two parameters you need to pass, the first is the key, and the second is a function that itself is given one parameter (the existing value). Example:

someMap.update("a", (value) => value + 100);

If you print the map after all of this you would get:

{a: 101, b: 2, c: 3}

Map<String, dynamic> someMap = {
  'id' : 10,
  'name' : 'Test Name'
};
someMethod(){
  someMap.addAll({
    'email' : '[email protected]'
  });
}
printMap(){
  print(someMap);
}

make sure you can't add entries right below the declaration.