6 Ways to iterate through a list in Dart and Flutter

Updated: September 11, 2023 By: A Goodman Post a comment

Iterating through a list is an essential skill in programming because it allows you to access and manipulate each element of the list in a sequential manner. This straightforward, example-based article will walk you through several different ways to loop over a given list in Dart (and Flutter as well). Without any further delay, let’s get to the main points.

Using a FOR loop

A for loop is a basic way of iterating over a list by using an index variable that goes from 0 to the length of the list minus one.

Example:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart';

void main() {
  // Declare and initialize a list of numbers
  List<int> numbers = [1, 2, 3, 4, 5];

  // Use a for loop to iterate over the list
  for (int index = 0; index < numbers.length; index++) {
    // Access the element at the index position and print its square
    int number = numbers[index];

    // Print the square of the number if in debug mode
    if (kDebugMode) {
      print(number * number);
    }
  }
}

Output:

1
4
9
16
25

This approach is simple and gives you full control over the iteration process and allows you to modify the index variable as needed.

Using a for-in loop

A for-in loop is a concise way of iterating over a list by using an element variable that takes the value of each element in the list sequentially. It avoids the need to use an index variable and access the list elements by position.

Example:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart';

void main() {
  // Declare and initialize a list of strings
  List<String> names = ["Goodman", "Badman", "Batman", "Spiderman"];

  // Use a for-in loop to iterate over the list
  for (String name in names) {
    // Print the element in uppercase
    debugPrint(name.toUpperCase());
  }
}

Output:

GOODMAN
BADMAN
BATMAN
SPIDERMAN

Using the forEach() method

The forEach() method gives us a functional way of iterating over a list by using a function that takes each element in the list as an argument and performs some operation on it.

Example:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart';

void main() {
  // Declare and initialize a list of booleans
  List<bool> flags = [true, false, true, false];

  // Define a function that takes a boolean as an argument and prints its negation
  void negate(bool flag) {
    if (kDebugMode) {
      print(!flag);
    }
  }

  // Call the forEach method on the list and pass the function as an argument
  flags.forEach(negate);
}

Output:

false
true
false
true

This approach is expressive and declarative. It can separate the logic of iterating over the list from the logic of performing some operation on each element.

While loop with index

You can also use a while loop with an index variable to iterate over the list elements.

Example:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart';

void main() {
  List<String> words = ['Hello', 'KindaCode', 'Flutter'];
  int i = 0;
  while (i < words.length) {
    debugPrint(words[i]);
    i++;
  }
}

Output:

Hello
KindaCode
Flutter

This solution is similar to using the for loop with index, but allows more flexibility in controlling the loop condition and increment. However, it is verbose and error-prone.

While loop with iterator

This is another way of using a while loop with an iterator object to iterate over the list elements.

Example:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart';

void main() {
  List<Map<String, dynamic>> products = [
    {
      "name": "Product 1",
      "price": 100,
    },
    {
      "name": "Product 2",
      "price": 200,
    },
    {
      "name": "Product 3",
      "price": 300,
    },
  ];

  Iterator<Map<String, dynamic>> it = products.iterator;
  while (it.moveNext()) {
    if (kDebugMode) {
      print(it.current);
    }
  }
}

Output:

{name: Product 1, price: 100}
{name: Product 2, price: 200}
{name: Product 3, price: 300}

This approach is generic, abstract, and works well with any iterable collection. However, it may be over-complicated, unfamiliar to some programmers, and does not allow you to access the index of the element.

Using the map() method

The map() method takes a function as an argument and returns a new list with the results of applying the function to each element of the original list. For example, you can use map() to create a new list with the lengths of each name in the original list:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart';

void main() {
  List<String> names = ["John Doe", "Foo Bar", "Kinda Code"];

  // using the map() method to get a list of names in uppercase
  List<String> uppercaseNames =
      names.map((name) => name.toUpperCase()).toList();

  if (kDebugMode) {
    print(uppercaseNames);
  }
}

Output:

[JOHN DOE, FOO BAR, KINDA CODE]

Conclusion

You’ve learned several techniques to iterate over a given list. Understanding these techniques deeply can help you solve most of programming tasks much easier. If you’d like to explore more new and interesting things in Flutter and Dart, take a look at the following articles:

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Related Articles