Dart for loop


The for loop in Dart is a control flow statement that allows you to execute a block of code repeatedly for a specified number of iterations. It is commonly used when you know the exact number of times you want to repeat a particular action, making it a powerful tool for iterating over ranges, collections, or performing repetitive tasks.

Syntax

The basic syntax of a for loop in Dart is as follows:

for (initialization; condition; increment) { // Code to execute on each iteration }
  • Initialization: This part is executed once at the beginning of the loop. It typically initializes a counter variable.
  • Condition: Before each iteration, the condition is evaluated. If it evaluates to true, the loop body executes. If it evaluates to false, the loop terminates.
  • Increment: This part is executed at the end of each iteration and typically updates the counter variable.

Example of a Basic for Loop

Here’s a simple example that demonstrates a basic for loop:

void main() { for (int i = 0; i < 5; i++) { print('Iteration: $i'); // Outputs: Iteration: 0, 1, 2, 3, 4 } }

Breakdown of the Example

  1. Initialization: int i = 0; initializes the loop counter i to 0.
  2. Condition: i < 5 checks if i is less than 5. As long as this condition is true, the loop continues to execute.
  3. Increment: i++ increments the value of i by 1 after each iteration.

Looping Through a Collection

The for loop can also be used to iterate through collections such as lists. Here’s an example:

void main() { List<String> fruits = ['Apple', 'Banana', 'Cherry']; for (int i = 0; i < fruits.length; i++) { print('Fruit: ${fruits[i]}'); // Outputs: Apple, Banana, Cherry } }

Nested for Loops

You can also nest for loops to perform multi-dimensional iterations. Here’s an example:

void main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { print('i: $i, j: $j'); } } }

Output:

i: 1, j: 1 i: 1, j: 2 i: 2, j: 1 i: 2, j: 2 i: 3, j: 1 i: 3, j: 2

Enhanced for Loop (For-Each Loop)

Dart also provides a more concise way to iterate over collections using the enhanced for loop (also known as the for-each loop):

Syntax:

for (var element in collection) { // Code to execute for each element }

Example:

void main() { List<String> fruits = ['Apple', 'Banana', 'Cherry']; for (var fruit in fruits) { print('Fruit: $fruit'); // Outputs: Apple, Banana, Cherry } }

Important Notes

  • Control Flow: You can use break to exit the loop prematurely and continue to skip the current iteration and proceed to the next one.
  • Scope: The loop variable (e.g., i) is scoped to the loop itself; it cannot be accessed outside of it.

Conclusion

The for loop in Dart is a versatile and powerful construct for iterating over ranges, collections, or performing repetitive tasks. Understanding how to use for loops effectively will enhance your programming skills and allow you to write efficient and clean code.