dart

Foreach Loop in Flutter [Dart]

In this post, we will learn to use ItearbleItem.forEach() function to iterate over a collection in Dart. There is no default foreach loop in Dart like other programming languages but it provides forEach() function that can be used for the same purpose.

List subjects = [
    {"id": 1, "name": "Math"},
    {"id": 2, "name": "Physics"},
    {"id": 3, "name": "Chemistry"}
];

subjects.forEach((subject) {
    // ... Do something here with items here
    print(subject["name"]);
});

The forEach() function in Dart or Flutter is used to iterate over a List or Map. We will explain different code examples here to show how you can use the forEach() function in Dart.

The forEach() function does not return anything but it is used as List.forEach() or Map.forEach() in Dart programming language.

Use List.forEach() to iterate over a List

We can use the forEach() function to iterate over a list of elements. We can access the elements inside the callback function of List.forEach() in each iteration. You can use the items to implement different tasks.

Below are some code examples that we are using for List iteration of different types.

Code Example 1

List numbers = [10, 20, 30, 40];

numbers.forEach((item) => print(item) );

Output

10
20
30
40

Code Example 2

List employees = [
  {"id": 1, "name": "Mohan"},
  {"id": 2, "name": "Rohit"},
  {"id": 3, "name": "Ganesh"},
  {"id": 4, "name": "Yogesh"}
];

employees.forEach((item) {
  print("${item["id"]}: ${item["name"]}");
});

Output

1: Mohan
2: Rohit
3: Ganesh
4: Yogesh

Use Map.forEach() to iterate over a Map

As shown in previous code examples we can easily iterate over a List using List.forEach() but you can also use Map.forEach() to iterate over a Map in Dart.

We will show some examples that will help you to understand the functionality of forEach() with collection type Map.

Code Example 1

Map user = {
  "id": 1,
  "name": "Cristen",
  "email": "[email protected]",
  "city": "New York"
};

user.forEach((key, value) {
  print("Key is: ${key}. Value is: ${value}");
});

Or the above code example can be written as below - using the lambda function

Map user = {
  "id": 1,
  "name": "Cristen",
  "email": "[email protected]",
  "city": "New York"
};

user.forEach((key, value) => print("Key is: ${key}. Value is: ${value}"));

Output

Key is: id. Value is: 1
Key is: name. Value is: Cristen
Key is: email. Value is: [email protected]
Key is: city. Value is: New York
Was this helpful?