To add a key-value pair to a map in Dart, you can use the subscript operator or the addAll method.
We can add a key-value pair to a map in Dart using the subscript operator, which adds an element with a specific key and value to the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Add a key-value pair using subscript operator
myMap['four'] = 4;
// Print the updated map
print(myMap);
}
{one: 1, two: 2, three: 3, four: 4}
We can add a key-value pair to a map in Dart using the addAll method, which adds all key-value pairs from another map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.addAll
method to add new key-value pairs to the map. The addAll
method takes another map containing the key-value pairs to be added.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Add a key-value pair using addAll method
myMap.addAll({'four': 4});
// Print the updated map
print(myMap);
}
{one: 1, two: 2, three: 3, four: 4}
We can add multiple key-value pairs to a map in Dart using the addAll method, which adds all key-value pairs from another map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.addAll
method to add multiple new key-value pairs to the map. The addAll
method takes another map containing the key-value pairs to be added.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Add multiple key-value pairs using addAll method
myMap.addAll({'four': 4, 'five': 5});
// Print the updated map
print(myMap);
}
{one: 1, two: 2, three: 3, four: 4, five: 5}
In this tutorial, we learned How to Add a Key-Value Pair to a Map in Dart language with well detailed examples.