Dart Loops
Dart provides several looping constructs that allow you to iterate over a set of instructions multiple times. Here’s an overview of the common loop types in Dart with examples:
1. `while` Loop
The `while` loop executes a block of code as long as the condition is true.
void main() { int i = 0; while (i < 5) { print('Iteration $i'); i++; } }
2. `do-while` Loop
The `do-while` loop is similar to the `while` loop, but it guarantees that the loop body will be executed at least once.
void main() { int i = 0; do { print('Iteration $i'); i++; } while (i < 5); }
3. `for` Loop
The `for` loop is used to execute a block of code a specified number of times.
void main() { for (int i = 0; i < 5; i++) { print('Iteration $i'); } }
4. `for-in` Loop
The `for-in` loop is used to iterate over the elements of a collection (like a list or a set).
void main() { List<String> fruits = ['Apple', 'Banana', 'Cherry']; for (var fruit in fruits) { print(fruit); } }
5.`forEach` Loop
The `forEach` method is used to execute a function for each element in a collection.
void main() { List<int> numbers = [1, 2, 3, 4, 5]; numbers.forEach((number) { print('Number: $number'); }); }
6. Nested Loops
You can nest loops within each other to perform more complex iterations.
void main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { print('i: $i, j: $j'); } } }
7. `break` and `continue` Statements
The `break` statement exits the loop immediately, and the `continue` statement skips to the next iteration of the loop.
Using `break`
void main() { for (int i = 0; i < 5; i++) { if (i == 3) { break; } print('Iteration $i'); } } ``` Using `continue` void main() { for (int i = 0; i < 5; i++) { if (i == 3) { continue; } print('Iteration $i'); } } ```