Different Types of Loops in Dart

Dart provides several types of loops that allow you to execute a block of code multiple times. The most commonly used loops in Dart are for, while, and do-while. Each loop has its own use cases and syntax. Below, we will explore each type of loop in detail with sample code.

1. for Loop

The for loop is used when you know in advance how many times you want to execute a block of code. It consists of three parts: initialization, condition, and increment/decrement.

void main() {
for (int i = 0; i < 5; i++) {
print('Iteration: $i');
}
}

In this example, the loop will execute 5 times, printing the iteration number from 0 to 4.

2. while Loop

The while loop is used when you want to execute a block of code as long as a specified condition is true. The condition is checked before each iteration.

void main() {
int count = 0;

while (count < 5) {
print('Count: $count');
count++; // Increment the count
}
}

In this example, the loop will continue to execute until count is no longer less than 5, printing the count from 0 to 4.

3. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once, as the condition is checked after the execution of the loop body.

void main() {
int count = 0;

do {
print('Count: $count');
count++; // Increment the count
} while (count < 5);
}

In this example, the loop will execute and print the count from 0 to 4, just like the while loop, but it ensures that the body is executed at least once.

4. for-in Loop

The for-in loop is used to iterate over elements in a collection, such as a list or a set. It simplifies the syntax for looping through collections.

void main() {
List<string> fruits = ['Apple', 'Banana', 'Cherry'];

for (var fruit in fruits) {
print('Fruit: $fruit');
}
}
</string>

In this example, the loop iterates over each fruit in the list and prints its name.

5. forEach Method

Dart also provides a forEach method for collections, which allows you to execute a function for each element in the collection.

void main() {
List<string> fruits = ['Apple', 'Banana', 'Cherry'];

fruits.forEach((fruit) {
print('Fruit: $fruit');
});
}
</string>

This example achieves the same result as the for-in loop, printing each fruit in the list.

Conclusion

Dart provides various types of loops to handle repetitive tasks efficiently. The choice of loop depends on the specific use case, such as whether you know the number of iterations in advance or need to iterate over a collection. Understanding these loops will help you write more effective and efficient Dart code.