Skip to main content

Iterating Through Lists

Iteration is the process of accessing each element in a list sequentially. Dart provides multiple ways to iterate through lists, each suited for different scenarios.

Using For-In Loop

The for-in loop is the simplest way to access each element in a list:
List<String> nombres = ['Juan', 'María', 'Pedro', 'Luisa'];

for (var nombre in nombres) {
  print(nombre);
}
Output:
Juan
María
Pedro
Luisa
Use for-in when you only need to read the values and don’t need to know the index position.

Searching While Iterating

You can search for specific elements while iterating through a list:
List<String> nombres = ['Juan', 'María', 'Pedro', 'Luisa'];
int posicion = 0;

for (var nombre in nombres) {
  if (nombre == 'Luisa') {
    print('Nombre encontrado en posición $posicion');
  }
  posicion++;
}
Output:
Nombre encontrado en posición 3
When using for-in and you need the index, you must manually track the position with a counter variable.

Using Indexed For Loop

When you need to modify elements or access indices directly, use a traditional for loop:
for (var i = 0; i < nombres.length; i++) {
  if (nombres[i] == 'Maria') {
    nombres[i] = 'María';
  }
}
You cannot modify list elements directly in a for-in loop. Use an indexed for loop instead when you need to change values.

Iteration Methods Comparison

MethodUse CaseCan Modify ElementsHas IndexSyntax Complexity
for-inReading valuesNoNo (manual tracking needed)Simple
Indexed forModifying elementsYesYesModerate
forEach()Functional approachNoNoSimple
map()Transforming elementsCreates new listNoModerate

Complete Example

void main() {
  //Programa para recorrer una lista de diversas maneras utilizando for in y for. 
  List<String> nombres = ['Juan', 'María', 'Pedro', 'Luisa', 'Maria'];
  
  //Recorrer o Iterar la Lista
  for (var nombre in nombres) {
    print(nombre);
  }
  
  //Buscar un elemento de la Lista
  int posicion = 0;
  for (var nombre in nombres) {
    if (nombre == 'Luisa'){
      print('Nombre encontrado en posición $posicion');
    }
    posicion++;
  }
  
  //Modificar el valor de un elemento de la lista
  for (var i = 0; i < nombres.length; i++) {
    if (nombres[i] == 'Maria')
      nombres[i] = 'María';
  }

  for (var nombre in nombres) {
    print(nombre);
  }
}

Common Iteration Patterns

Pattern 1: Simple Iteration

Just access each element:
for (var item in list) {
  print(item);
}

Pattern 2: Search with Position

Find an element and get its index:
int index = 0;
for (var item in list) {
  if (item == searchValue) {
    print('Found at position $index');
    break; // Stop after finding
  }
  index++;
}

Pattern 3: Modify Elements

Change values based on conditions:
for (var i = 0; i < list.length; i++) {
  if (condition) {
    list[i] = newValue;
  }
}

Pattern 4: Filter Elements

Collect matching elements:
List<String> filtered = [];
for (var item in list) {
  if (condition) {
    filtered.add(item);
  }
}

Working with Empty Lists

Always check if a list has elements before iterating, especially when working with user input:
if (nombres.isNotEmpty) {
  for (var nombre in nombres) {
    print(nombre);
  }
} else {
  print('La lista está vacía');
}

Advanced Iteration Methods

Using forEach()

Functional approach with a callback:
nombres.forEach((nombre) {
  print(nombre);
});

Using map()

Transform each element into a new list:
List<String> upperNames = nombres.map((nombre) => nombre.toUpperCase()).toList();

Using where()

Filter elements based on a condition:
List<String> filteredNames = nombres.where((nombre) => nombre.startsWith('M')).toList();

Performance Considerations

For-In Loop

Most readable and efficient for simple iteration

Indexed For

Best when you need to modify elements or access indices

forEach()

Good for functional programming style

map/where

Ideal for transforming or filtering data

Choosing the Right Method

  1. Use for-in when you just need to read values
  2. Use indexed for when you need to modify elements or use indices
  3. Use forEach() for functional programming style
  4. Use map() or where() for transformations and filtering
Avoid modifying a list’s length (adding/removing elements) while iterating through it, as this can cause unexpected behavior or errors.

Build docs developers (and LLMs) love