A loop executes the same block several times. This helps when a vehicle list contains ten vehicles rather than one. You write the output rule once. A for-in loop visits each value in a collection. A traditional for loop also maintains a counter.
01Visit a list
Square brackets create a list. for (final name in names) sets the current name for each iteration. It does not create another permanently stored vehicle record. We are only reading values here.
void main() {
final names = ['Family car', 'Motorbike'];
for (final name in names) {
print(name);
}
for (var i = 0; i < names.length; i++) {
print('${i + 1}: ${names[i]}');
}
}
Run / check
dart run loops.dart02Work with an index
i starts at 0. i < names.length prevents access beyond the list. i++ increases the index after each iteration. The first item has index 0 rather than 1.
03Avoid infinite repetition
A while loop repeats its block while its condition remains true. The block must eventually change the state or exit with break. For a known list, for-in is usually easier to read.
Family car and Motorbike are each printed twice.
Your exercise
Print only names starting with M.
Show the solution and explanation
Inside for-in, use if (name.startsWith("M")) to check whether the current name matches. The example prints only Motorbike. The loop still visits both names.
Project context and sources
The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.