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):
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:
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 beforedo-while: runs at least once
switch expression
- Returns a value with
=> _as a wildcard
💪 Practical Exercise
Practice loops and switch
- Write a
do-whilethat asks for a number until it's positive. - Iterate over a list with
for-inusingbreakto stop when you find a negative number. - Convert an
if/else iffor days of the week into aswitchexpression 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,
};