To get the size (number of key-value pairs) of a map in Dart, you can use the length property. This property returns the number of elements in the map.
We can get the size of a map in Dart using the length property, which provides the number of key-value pairs in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.length
property to get the number of key-value pairs in the map.mapSize
.print
function to verify the number of key-value pairs in the map.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Get the size of the map
int mapSize = myMap.length;
// Print the size
print('Size of the map: $mapSize');
}
Size of the map: 3
We can also get the size of an empty map in Dart using the length property, which returns 0 when the map is empty.
For example,
emptyMap
with string keys and integer values.length
property to get the number of key-value pairs in the empty map.emptyMapSize
.print
function to verify that the map is empty.void main() {
// Declare an empty map
Map<String, int> emptyMap = {};
// Get the size of the empty map
int emptyMapSize = emptyMap.length;
// Print the size
print('Size of the empty map: $emptyMapSize');
}
Size of the empty map: 0
We can get the size of a map in Dart after adding elements using the length property, which provides the updated number of key-value pairs in the map.
For example,
dynamicMap
with string keys and integer values.length
property to get the number of key-value pairs in the map after adding elements.dynamicMapSize
.print
function to verify the updated number of key-value pairs in the map.void main() {
// Declare an empty map
Map<String, int> dynamicMap = {};
// Add elements to the map
dynamicMap['one'] = 1;
dynamicMap['two'] = 2;
dynamicMap['three'] = 3;
// Get the size of the map after adding elements
int dynamicMapSize = dynamicMap.length;
// Print the size
print('Size of the map after adding elements: $dynamicMapSize');
}
Size of the map after adding elements: 3
In this tutorial, we learned How to Get the Size (Number of Key-Value Pairs) of a Map in Dart language with well detailed examples.