Dart: Control Flow

for classic, for-in, while and the switch expression in Dart 3

🔁 1. Loops: for, for-in and while

Execution trace (suma = 108):

Step 1: suma += 4 → total = 4
Step 2: suma += 8 → total = 12
Step 3: suma += 15 → total = 27
Step 4: suma += 16 → total = 43
Step 5: suma += 23 → total = 66
Step 6: suma += 42 → total = 108

Try with your own list

Dart Code (for in):

int suma = 0;
for (final n in numeros) {
  suma += n;
}print(suma); // 108
💡 ¿Cuál elegir?

for-in is the most idiomatic way in Dart when you only need to iterate over the elements. Use the for classic one when you need the index, and while when you don't know beforehand how many iterations will be needed.

🔀 2. switch as an expression (Dart 3)

Result:

calificar(7.5)
Very Good

Try a grade

String calificar(double nota) => switch (nota) {
  >= 9 => 'Sobresaliente',
  >= 7 => 'Notable',
  >= 5 => 'Bien',
  >= 4 => 'Suficiente',
  _    => 'Insuficiente',
};
💡 switch como expresión

Since Dart 3, switch can be used as an expression (it returns a value directly with =>), without needing break. The wildcard _ acts as the default.

🎯 Key Concepts

for-in

  • Traverses any Iterable
  • More readable than the classic for classic

while / do-while

  • while: checks before
  • do-while: runs at least once

switch expression

  • Returns a value with =>
  • _ as a wildcard

💪 Practical Exercise

Practice loops and switch

  1. Write a do-while that asks for a number until it's positive.
  2. Iterate over a list with for-in using break to stop when you find a negative number.
  3. Convert an if/else if for days of the week into a switch expression that returns whether it's a weekend.

Solution 1

int numero;
do {
  numero = obtenerNumero();
} while (numero <= 0);

Solution 2

for (final n in numeros) {
  if (n < 0) break;
  print(n);
}

Solution 3

bool esFinDeSemana(String dia) => switch (dia) {
  'sábado' || 'domingo' => true,
  _ => false,
};