In Dart, writing a basic for loop is pretty straightforward. The for loop is mainly used when you know the number of iterations in advance. The syntax includes three parts: initialization, condition, and increment/decrement.
For example, if I wanted to print numbers from 1 to 5, I would write:
for (int i = 1; i <= 5; i++) {
print(i);
}
Here, int i = 1 initializes the counter, i <= 5 is the condition that keeps the loop running, and i++ increments the counter in each iteration.
I’ve applied for loops frequently when iterating over lists, like processing a list of user names to display them in a UI or performing batch operations on a set of data. One challenge I faced early on was trying to modify a list inside a for loop while iterating over it — it caused unexpected behavior. I learned that in such cases, using a forEach method or iterating over a copy of the list is safer.
As an alternative, Dart also provides for-in loops which are cleaner when iterating over collections:
List names = ['Alice', 'Bob', 'Charlie'];
for (var name in names) {
print(name);
}
This avoids manual index handling and reduces chances of off-by-one errors, which I often prefer in practical projects.
