Add new element to map dart
In Dart, you can add a new element to a Map
using the putIfAbsent
method or the []
operator.
Here are some examples:
Using putIfAbsent
method
Map<String, int> myMap = {'a': 1, 'b': 2};
myMap.putIfAbsent('c', () => 3); // adds 'c': 3 to the map if it doesn't exist
print(myMap); // Output: {'a': 1, 'b': 2, 'c': 3}
Using []
operator
Map<String, int> myMap = {'a': 1, 'b': 2};
myMap['c'] = 3; // adds 'c': 3 to the map if it doesn't exist
print(myMap); // Output: {'a': 1, 'b': 2, 'c': 3}
In both cases, if the key 'c'
already exists in the map, the value associated with it will be updated.
Note: If you want to add a new element to a Map
and return the new value, you can use the putIfAbsent
method with a callback function that returns the new value. For example:
Map<String, int> myMap = {'a': 1, 'b': 2};
int newValue = myMap.putIfAbsent('c', () => 3 + 4); // adds 'c': 7 to the map if it doesn't exist
print(myMap); // Output: {'a': 1, 'b': 2, 'c': 7}
print(newValue); // Output: 7