Loops

1. Standard for Loop

Syntax: for(initialization; condition; iterator) { loop body }

1: Basic String Concatenation

void main() {
  var message = StringBuffer('welcome to FoxDevelop.com');
  for (var i = 0; i < 5; i++) {
    message.write('!');
  }
  print(message); // welcome to FoxDevelop.com!!!!!
}Code language: Dart (dart)

This loop runs from 0 to 5 (exclusive), meaning i takes values 0 through 4 for a total of 5 iterations. Each iteration appends an exclamation mark to the end of the string welcome to FoxDevelop.com.

1st iteration: welcome to FoxDevelop.com!

2nd iteration: welcome to FoxDevelop.com!!

5th iteration: welcome to FoxDevelop.com!!!!!

Feature: Closure Captures Separate Index (Key Difference from JavaScript)

Dart binds an independent copy of variable i for every loop iteration, which avoids the classic JavaScript pitfall where all callbacks print the final value 2.

void main() {
  var callbacks = [];
  for (var i = 0; i < 2; i++) {
    callbacks.add(() => print(i));
  }
  for (final c in callbacks) {
    c();
  }
}
// Output
// 0
// 1
Code language: Dart (dart)

2. for-in Loop for Iterable Collections (List/Set)

Best suited for scenarios where you only need element values without their indexes.

Basic Usage

class Candidate {
  void interview() => print("Interview completed");
}

void main() {
  var candidates = [Candidate(), Candidate()];
  for (var candidate in candidates) {
    candidate.interview();
  }
}Code language: Dart (dart)

Iterates over the candidates list, assigns each element to variable candidate, then calls its interview() method. The iterator automatically advances to the next item after each loop cycle.

Advanced Usage

Object Pattern Destructuring with for-in (Dart 3+)

class Candidate {
  final String name;
  final int yearsExperience;
  Candidate({required this.name, required this.yearsExperience});
}

void main() {
  var candidates = [
    Candidate(name: "Lily", yearsExperience: 6),
    Candidate(name: "Tom", yearsExperience: 3),
  ];

  // Directly destructure class fields via object pattern
  for (final Candidate(:name, :yearsExperience) in candidates) {
    print('$name has $yearsExperience years of working experience');
  }
}
Code language: Dart (dart)

Combines pattern matching to extract the two class properties into standalone variables name and yearsExperience, which can be used directly inside the loop body.

3. Iterable.forEach() Iteration Method

Functional-style built-in iterator for all collection types; accepts a callback to handle each element.

void main() {
  var collection = [1, 2, 3];
  collection.forEach(print);
  // Output: 1 2 3
}Code language: Dart (dart)

forEach is a native Dart method available on every iterable collection type.

4. while / do-while Loops

1. while Loop

Evaluates the condition first before executing the body; the loop body may never run at all. Behaves identically to C, C++, Java, C# and other mainstream languages.

bool isDone() => false;
void doSomething() => print("Executing task");

void main() {
  while (!isDone()) {
    doSomething();
    break;
  }
}Code language: Dart (dart)

The condition !isDone() evaluates to true since isDone() returns false, so the inner block runs:

doSomething();
break;

The break keyword terminates the loop immediately and jumps to the code after the while block. If isDone() returned true, the condition would fail on the first check and the loop body would never execute.

2. do-while Loop

Runs the loop body once unconditionally, then evaluates the condition; guarantees at least one execution.

bool atEndOfPage() => true;
void printLine() => print("Print one line");

void main() {
  do {
    printLine();
  } while (!atEndOfPage());
}
Code language: Dart (dart)

Code inside the do {} block will always execute exactly once, regardless of whether the trailing while condition resolves to true or false.

5. break / continue Control Keywords

break

Terminates the entire loop instantly and skips all remaining code inside the loop body.

bool shutDownRequested() => true;
void processIncomingRequests() => print("Processing requests");

void main() {
  while (true) {
    if (shutDownRequested()) break;
    processIncomingRequests();
  }
  print("Loop finished");
}
Code language: Dart (dart)

continue

Skips all remaining statements in the current iteration and jumps directly to the start of the next loop cycle.

Traditional for Loop Example
class Candidate {
  final int yearsExperience;
  Candidate(this.yearsExperience);
  void interview() => print("Running interview");
}

void main() {
  var candidates = [Candidate(3), Candidate(6)];
  for (int i = 0; i < candidates.length; i++) {
    var candidate = candidates[i];
    if (candidate.yearsExperience < 5) {
      continue; // Skip interview for candidates with less than 5 years of experience
    }
    candidate.interview();
  }
}
Code language: Dart (dart)
Functional Alternative (No continue Required)
void main() {
  var candidates = [Candidate(3), Candidate(6)];
  candidates
      .where((c) => c.yearsExperience >= 5)
      .forEach((c) => c.interview());
}
Code language: Dart (dart)

6. Labeled Loops for Nested Loop Control

Syntax: Place labelName: before a loop, then use break labelName / continue labelName

Purpose: When working with nested loops, break or skip the outer loop directly instead of only affecting the innermost loop.

1. break + Label

Exit a double nested loop immediately

void main() {
  outerLoop:
  for (var i = 1; i <= 3; i++) {
    for (var j = 1; j <= 3; j++) {
      print('i = $i, j = $j');
      if (i == 2 && j == 2) {
        break outerLoop; // Terminate the outer loop marked outerLoop
      }
    }
  }
  print('outerLoop exited');
}
Code language: Dart (dart)

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
outerLoop exited
Code language: Dart (dart)

2. continue + Label

Jump straight to the next iteration of the outer loop

void main() {
  outerLoop:
  for (var i = 1; i <= 3; i++) {
    for (var j = 1; j <= 3; j++) {
      if (i == 2 && j == 2) {
        continue outerLoop; // Skip remaining j values for i=2, jump to i=3
      }
      print('i = $i, j = $j');
    }
  }
}
Code language: Dart (dart)

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

while + break + Label Example

void main() {
  var i = 1;
  outerLoop:
  while (i <= 3) {
    var j = 1;
    while (j <= 3) {
      print('i = $i, j = $j');
      if (i == 2 && j == 2) {
        break outerLoop;
      }
      j++;
    }
    i++;
  }
  print('outerLoop exited');
}
Code language: PHP (php)

Execution Result

D:\dartdemo\firstdart>dart run
Building package executable...
Built firstdart:firstdart.
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
outerLoop exited

This mechanism behaves similarly to the goto statement found in other programming languages.

Loops

Leave a Reply

Your email address will not be published. Required fields are marked *