How to use for loops in Flutter

Flutter Jul 31, 2023

For loops are essential in programming, allowing developers to execute a block of code repeatedly based on specific conditions. In Flutter, for loops are commonly used for iterating over lists, maps, or performing a certain number of times. Let us go over various examples of for loops in Flutter to see how they can be used.

1. Traditional for loop

The most commonly used loop in Flutter is the "for loop". It allows us to repeat a task multiple times. The for loop has three parts:

  1. Starting point: We set the initial value.
  2. Condition: We define when the loop should continue running.
  3. Increment (or decrement) step: We specify how the value should change after each repetition.

1.1 Regular for loop

void main() {
  for (int index = 0; index < 5; index++) {
    print("Iteration $index");
  }
}

This example shows a traditional for loop in Flutter. The loop runs from index = 0 to index = 4. In each iteration, it prints "Iteration" followed by the current value of the index variable. The index is incremented after each iteration using index++, which is a shorthand for index = index + 1 or index += 1.

Resulting Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

1.2 Incrementing the index inside the code block

void main() {
  for (int index = 0; index < 5;) {
    print("Iteration $index");

    index++;
  }
}

In this code snippet, we increment the index inside the for loop's code block. The loop runs from index = 0 to index = 4, and the increment statement index++ is placed inside the code block. This increments the index variable after each iteration. The output remains the same as in the previous example. However, this makes it possible to conditionally increment the index.

Resulting Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

1.3 Using a for loop to count down

void main() {
  for (int index = 4; index >= 0; index--) {
    print("Iteration $index");
  }
}

This code snippet demonstrates a for loop used to count down from index = 4 to index = 0. The loop runs as long as index is greater than or equal to 0, and in each iteration, it prints "Iteration" followed by the current value of the index variable. This results in a countdown, displaying the values of index in reverse order.

Resulting output:

Iteration 4
Iteration 3
Iteration 2
Iteration 1
Iteration 0

2. Looping over lists

When working with collections of data in Flutter, it is common to have a list of items that you need to process or display. Fortunately, Flutter provides multiple ways to loop over lists, making it easy to perform operations on each element efficiently.

2.1 Using regular for loop

void main() {
  List<String> animals = ['Bird', 'Elephant', 'Snake'];

  for (int index = 0; index < animals.length; index++) {
    print(animals[index]);
  }
}

This example demonstrates using a regular for loop to iterate over a list of animals. The loop runs from index = 0 to index = animals.length - 1, and in each iteration, it prints the animal corresponding to the current index.

Resulting Output:

Bird
Elephant
Snake

2.2 Using for-in loop

void main() {
  List<String> animals = ['Bird', 'Elephant', 'Snake'];

  for (String animal in animals) {
    print(animal);
  }
}

In this example, we use a for-in loop (enhanced for loop) to directly iterate over the elements of the animals list. In each iteration, the loop assigns the current animal to the animal variable, and then prints it inside the codeblock.

Resulting Output:

Bird
Elephant
Snake

2.3 Using forEach

void main() {
  List<String> animals = ['Bird', 'Elephant', 'Snake'];

  animals.forEach((animal) {
    print(animal);
  });
}

In Flutter, the forEach function is a easy way to iterate over elements in a list or iterable without requiring a for loop. In this example, we use forEach to loop over the animals list and execute a callback function for each animal, which simply prints the animal.

Resulting Output:

Bird
Elephant
Snake

3. Looping over maps

Other than looping over a list it is also possible to loop over maps in Flutter. In Flutter, maps are collections that associate key-value pairs, making them useful for organizing and accessing data.

3.1 Using for-in loop

void main() {
  Map<String, String> mascots = {
    'Bird': 'Flutter',
    'Elephant': 'PHP',
    'Snake': 'Python',
  };

 for (var entry in mascots.entries) {
   print('The mascot of ${entry.value} is a ${entry.key}.');
  };
}

In this example, we have a map named mascots that associates animals with programming languages. The for-in loop iterates over mascots.entries, which gives us a set of key-value pairs. We then extract the key (animal) and value (language) from each pair and use them in our print statement.

Resulting Output:

The mascot of Flutter is a Bird.
The mascot of PHP is a Elephant.
The mascot of Python is a Snake.

3.1 forEach

void main() {
  Map<String, String> mascots = {
    'Bird': 'Flutter',
    'Elephant': 'PHP',
    'Snake': 'Python',
  };

  mascots.forEach((animal, language) {
    print('The mascot of $language is a $animal.');
  });
}

The forEach() method is another way to loop over the elements of the mascots map. We pass a callback function that takes both the key animal and value language as arguments. The function is executed for each key-value pair in the map.

Resulting Output:

The mascot of Flutter is a Bird.
The mascot of PHP is a Elephant.
The mascot of Python is a Snake.

Conclusion

In conclusion, learning how to use for loops in Flutter is important for efficiently going through lists and maps, as well as for doing tasks that need to be repeated. In this post, we went over multiple techniques for common use cases. Understanding these techniques can make Flutter development easier and help you create better applications.

Tags