Loops
for, while, do-while, and for-in loops, plus break and continue for controlling iteration.
2 min read
Dart gives you the same core loop constructs as most C-family languages, plus a collection-friendly for-in form you'll use constantly once you start working with lists.
The classic for loop
for (int i = 0; i < 5; i++) {
print('Count: $i');
}The three parts — initializer, condition, increment — run in the order you'd expect: initialize once, check the condition before every iteration, and run the increment after each pass through the body.
for-in: iterating a collection
When you're looping over the elements of something iterable (a List, Set, or Map), for-in is clearer than tracking an index manually:
final languages = ['Dart', 'Python', 'Rust'];
for (final language in languages) {
print(language);
}Use for-in by default when you just need each element; reach for the index-based for loop only when you actually need the index itself, or need to skip around non-sequentially.
while and do-while
int attempts = 0;
while (attempts < 3) {
print('Attempt ${attempts + 1}');
attempts++;
}while checks its condition before running the body, so it can run zero times. do-while checks after, guaranteeing at least one run:
int input = -1;
do {
print('Requesting input...');
input = 5; // pretend this came from a user
} while (input < 0);Choose do-while specifically when the body needs to happen at least once regardless of the condition — a common example is prompting a user and only then checking whether their answer was valid.
break and continue
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // skip this iteration, keep looping
if (i == 6) break; // stop the loop entirely
print(i);
}
// prints: 0 1 2 4 5continue skips straight to the next iteration; break exits the loop immediately, and execution resumes right after it. Both work inside any of Dart's loop types, not just for.
Iterating a Map
Maps don't hand you a single value per iteration — you typically want both the key and the value, which .entries gives you:
final prices = {'apple': 1.5, 'bread': 3.2, 'milk': 2.0};
for (final entry in prices.entries) {
print('${entry.key}: \$${entry.value}');
}We'll cover Map itself in detail in the collections section — for now, notice that the loop mechanics don't change at all; only what you're iterating over does.