Maps in Dart
Maps
In a map, data is stored in the form of keys and values. Key occurs only once but we can use the same value multiple times. They are similar to HashMaps and Dictionaries in other languages.
How To Create Map In Dart
Here we are creating a map for String
and String
. You can create a map of any type.
void main(){
Map<String, String> countryCapital = {
'USA': 'Washington, D.C.',
'India': 'New Delhi',
'China': 'Beijing'
};
print(countryCapital);
}
- Here
Usa
India
andChina
are keys and keys of map should be unique.
Access Value From Key
You can access value from the key. Here we are printing Washington, D.C.
by its key i.e USA
.
void main(){
Map<String, String> countryCapital = {
'USA': 'Washington, D.C.',
'India': 'New Delhi',
'China': 'Beijing'
};
print(countryCapital["USA"]);
}
Adding Element To Map
void main(){
Map<String, String> countryCapital = {
'USA': 'Washington, D.C.',
'India': 'New Delhi',
'China': 'Beijing'
};
// Adding New Item
countryCapital['Japan'] = 'Tokio';
print(countryCapital);
}
Updating An Element Of Map
void main(){
Map<String, String> countryCapital = {
'USA': 'Nothing',
'India': 'New Delhi',
'China': 'Beijing'
};
// Updating Item
countryCapital['USA'] = 'Washington, D.C.';
print(countryCapital);
}
Removing Items From MAP
void main(){
Map<String, String> countryCapital = {
'USA': 'Nothing',
'India': 'New Delhi',
'China': 'Beijing'
};
countryCapital.remove("USA");
print(countryCapital);
}
MAP Properties In Dart
Properties | Work |
---|---|
isEmpty | Return true or false. |
isNotEmpty | Return true or false. |
keys | To get all keys. |
values | To get all values. |
values.toList() | Convert all maps values to List. |
containsKey(‘key’) | Return true or false. |
containsValue(‘value’) | Return true or false. |
Looping Over Element Of Map
void main(){
Map<String, dynamic> book = {
'title': 'Misson Mangal',
'author': 'Kuber Singh',
'page': 233
};
// Loop Through Map
for(MapEntry book in book.entries){
print('Key is ${book.key}, value ${book.value}');
}
}
Looping In Map Using For Each
void main(){
Map<String, dynamic> book = {
'title': 'Misson Mangal',
'author': 'Kuber Singh',
'page': 233
};
// Loop Through For Each
book.forEach((key,value)=> print('Key is $key and value is $value'));
}