To create a map with initial key-value pairs in Dart, you can use the map literal syntax. This creates a new map object with predefined key-value pairs.
We can create a map in Dart with initial key-value pairs using the map literal syntax, which initializes a map with predefined key-value pairs.
For example,
myMap
. This variable will hold our map with initial key-value pairs.myMap
variable. In this example, the map has string keys and integer values.void main() {
// Declare a map with initial key-value pairs
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Operations on the map
myMap.forEach((key, value) {
print('$key: $value');
});
}
one: 1 two: 2 three: 3
We can create a map in Dart with initial key-value pairs of different types using the map literal syntax.
For example,
studentGrades
. This variable will hold our map with initial key-value pairs where keys are strings (student names) and values are characters (grades).studentGrades
variable. In this example, the map has string keys and string values representing grades.void main() {
// Declare a map with initial key-value pairs
Map<String, String> studentGrades = {
'Alice': 'A',
'Bob': 'B',
'Charlie': 'C'
};
// Operations on the map
studentGrades.forEach((key, value) {
print('$key: $value');
});
}
Alice: A Bob: B Charlie: C
We can create a map in Dart with initial key-value pairs where keys are integers and values are doubles using the map literal syntax.
For example,
productPrices
. This variable will hold our map with initial key-value pairs where keys are integers (product IDs) and values are doubles (prices).productPrices
variable. In this example, the map has integer keys and double values.void main() {
// Declare a map with initial key-value pairs
Map<int, double> productPrices = {
101: 29.99,
102: 39.99,
103: 49.99
};
// Operations on the map
productPrices.forEach((key, value) {
print('Product $key: $value');
});
}
Product 101: 29.99 Product 102: 39.99 Product 103: 49.99
In this tutorial, we learned How to create a Map with Initial Key-Value Pairs in Dart language with well detailed examples.