To get the value associated with a key in a map in Dart, you can use the square bracket notation or the map's lookup method. These methods allow you to access the value directly using the key.
We can get the value associated with a key in a map in Dart using the square bracket notation, which returns the value associated with the specified key.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.'two'
. The square bracket notation returns the value associated with the specified key.value
.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Get the value associated with a key using square bracket notation
int? value = myMap['two'];
// Print the value
print('The value associated with key "two" is: $value');
}
The value associated with key "two" is: 2
We can get the value associated with a key in a map in Dart using the lookup method, which returns the value associated with the specified key.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.lookup
method to access the value associated with the key 'three'
. The lookup
method returns the value associated with the specified key.value
.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Get the value associated with a key using lookup method
int? value = myMap['three'];
// Print the value
print('The value associated with key "three" is: $value');
}
The value associated with key "three" is: 3
We can handle the case where a key is not found in a map in Dart using the square bracket notation, which returns null if the key is not present.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.'four'
. The square bracket notation returns null if the key is not found.value
.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Attempt to get the value associated with a non-existent key
int? value = myMap['four'];
// Print the result
if (value == null) {
print('Key "four" not found in the map.');
} else {
print('The value associated with key "four" is: $value');
}
}
Key "four" not found in the map.
In this tutorial, we learned How to Get the Value Associated with a Key in a Map in Dart language with well detailed examples.