Loops in Dart a similar to loops in the C style languages. You have conditional loops (the while and do while) and counting loop (for). Additionally you have a for…in loop (like a for each).
The For Loop
This is identical to your for loop in C/C++/Java.
void main() {
for(int i = 0; i < 10; i++) {
print(i);
}
}
This loop is good for going through a list, or doing a set of tasks a specific amount of times.
While Loop
The while loop is a standard pre-test conditional loop available to most languages.
You have your standard while command, and a condition within it. The loop body will execute while the condition is still met. You can create a counter loop with a while, but it is usually not as efficient or easy.
void main()
{
var counter = 0;
var maxValue =5;
while(counter <=maxValue){
print(counter);
counter++;
}
}
The Do While Loop
The do while loop is similar to the while loop, in that it is conditional, however it is a post test loop, so it does the loop body, then checks to see if the condition to see if the loop body should run again.
It will always execute the loop body at least one time.
The For .. in Loop
Given that Dart has several types of collection objects, it is good that it has a For..in loop.
The loop will have a temp variables, and an expression, or object that can be iterated over. It will perform the loop for every element in the expression.
for (var in expression) {
// Statement(s)
}
An example of this might be:
void main() {
var myList = [1,3,5,7,11,13,17,29,31,37];
for( var temp in myList) {
print(temp);
}
}
Notice how the for loop, is only for, it is called for..in because we define the temp variable, and then specify in the expression.
Loops in Dart was originally found on Access 2 Learn