Reputation: 4562
I caught the following errors when adding a new pair to a Map.
Variables must be declared using the keywords const, final, var, or a type name
Expected to find;
the name someMap is already defined
I executed the following code.
Map<String, int> someMap = {
"a": 1,
"b": 2,
};
someMap["c"] = 3;
How should I add a new pair to the Map?
I'd also like to know how to use Map.update
.
Upvotes: 144
Views: 276706
Reputation: 2963
This way is also applicable:
Map<String, int> someMap = {
"a": 1,
"b": 2,
};
someMap.addEntries({"c":3}.entries);
Upvotes: 12
Reputation: 10680
I write this utility:
Map updateMap({
/// Update a map with another map
/// Example:
/// Map map1 = {'name': 'Omid', }
/// Map map2 = {'family': 'Raha', }
/// Map map = updateMap(data:map1, update:map2);
/// Result:
/// map = {'name': 'Omid', 'family': 'Raha',}
@required Map data,
@required Map update,
}) {
if (update == null) return data;
update.forEach((key, value) {
data[key] = value;
});
return data;
}
Example:
Map map1 = {'name': 'Omid', }
Map map2 = {'family': 'Raha', }
Map map = updateMap(data:map1, update:map2);
print(map);
{'name': 'Omid', 'family': 'Raha',}
Upvotes: 1
Reputation: 671
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.
Upvotes: 17
Reputation: 3026
Another way to add new key/value as map to existing map is this,
oldMap.addEntries(myMap.entries);
This will update the oldMap
with key/value of myMap
;
Upvotes: 5
Reputation: 512346
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.
Upvotes: 60
Reputation: 18187
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}
Upvotes: 222