How to Iterate Through a Map in Dart

In the Dart programming language, maps are an important data structure for storing key-value pairs. Maps allow you to access values by using their keys and provide ordered relationships among them with order preserved across removes or additions of elements at any point in time – just like how Python dictionaries work!

Iterating through a map in Dart can be done in a few different ways. In this blog post, we will take a look at how to iterate through a map using the for…in loop, while loop, and forEach method.

Map<int, String> products = {
  2: "Amethyst +Strawberry Crystal",
  5: "Bag Charm",
  7: "Christmas Charms",
  11: "Lenovo Legion",
  57: "Asus ROG Strix",
  102: "HP pavilion",
};

products.forEach((key, value) {
  print("$key: $value");
});
for(var key in products.keys){
  print("$key: $map[$key]");
}
for (MapEntry e in products.entries) {
  print("${e.key}: ${e.value}");
}
for (var value in products.values) {
  print(value);
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close