flutter
/

Dart Loops – For, While, Do-While and Iteration

Last Sync: Today

On this page

13
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Loops – For, While, Do-While and Iteration

What are Loops?

Loops are used to execute a block of code repeatedly. They are essential for iterating over collections, performing repetitive tasks, and controlling program flow. Dart provides several types of loops to handle different iteration scenarios.

  1. The for Loop

The classic for loop repeats a block of code a specific number of times. It consists of three parts: initialization, condition, and increment/decrement.

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

  1. The for-in Loop

The for-in loop simplifies iterating over collections like lists, sets, and maps. It automatically extracts each element.

DARTRead-only
1
void main() {
  List<String> names = ['Alice', 'Bob', 'Charlie'];
  
  for (var name in names) {
    print('Hello, $name');
  }
}

  1. The while Loop

The while loop executes a block of code as long as a given condition is true. The condition is checked before each iteration.

DARTRead-only
1
void main() {
  int count = 0;
  
  while (count < 3) {
    print('Count: $count');
    count++;
  }
}

  1. The do-while Loop

The do-while loop is similar to while, but it guarantees that the code block executes at least once because the condition is checked after the iteration.

DARTRead-only
1
void main() {
  int number = 5;
  
  do {
    print('Number is $number');
    number--;
  } while (number > 0);
}

  1. The forEach() Method

Dart collections have a forEach() method that applies a function to each element. It's a functional alternative to loops.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4, 5];
  
  numbers.forEach((num) {
    print('Square of $num is ${num * num}');
  });
}

  1. Loop Control: break and continue

Use break to exit a loop prematurely, and continue to skip the current iteration and move to the next.

DARTRead-only
1
void main() {
  for (int i = 0; i < 10; i++) {
    if (i == 5) break;        // exit loop when i is 5
    if (i % 2 == 0) continue; // skip even numbers
    print(i);
  }
}

  1. Labeled Loops

When you have nested loops, you can use labels with break or continue to specify which loop to affect.

DARTRead-only
1
void main() {
  outerLoop: for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      if (i == 1 && j == 1) break outerLoop;
      print('i = $i, j = $j');
    }
  }
}

Complete Examples

Here are more practical examples demonstrating loops in action:

Example 1: Sum of Numbers

DARTRead-only
1
void main() {
  int sum = 0;
  for (int i = 1; i <= 10; i++) {
    sum += i;
  }
  print('Sum of 1 to 10 is $sum'); // 55
}

Example 2: Iterating a Map

DARTRead-only
1
void main() {
  Map<String, int> ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35};
  
  ages.forEach((name, age) {
    print('$name is $age years old');
  });
}

Example 3: Finding Prime Numbers

DARTRead-only
1
bool isPrime(int n) {
  if (n <= 1) return false;
  for (int i = 2; i <= n ~/ 2; i++) {
    if (n % i == 0) return false;
  }
  return true;
}

void main() {
  for (int i = 2; i <= 20; i++) {
    if (isPrime(i)) {
      print('$i is prime');
    }
  }
}

Key Takeaways

    • Use for loop when you know the number of iterations in advance.
    • Use for-in to iterate over collections concisely.
    • Use while when the number of iterations is unknown and depends on a condition.
    • Use do-while when you need the loop body to execute at least once.
    • forEach() provides a functional way to process each element.
    • break exits a loop; continue skips to the next iteration.
    • Labels help control nested loops.

Try it yourself

void main() {
  // Write a loop to print numbers 1 to 5
  for (int i = 1; i <= 5; i++) {
    print(i);
  }
}

Test Your Knowledge

Q1
of 4

What is the output of this code? void main() { for (int i = 0; i < 3; i++) { if (i == 1) continue; print(i); } }

A
0 1 2
B
0 2
C
0 1
D
1 2
Q2
of 4

Which loop guarantees at least one execution?

A
for
B
while
C
do-while
D
for-in
Q3
of 4

What keyword is used to exit a loop immediately?

A
exit
B
break
C
stop
D
return
Q4
of 4

Which loop is best for iterating over all elements of a list?

A
for with index
B
while
C
do-while
D
for-in

Frequently Asked Questions

What is the difference between `for` and `for-in` loops?

The for loop gives you an index and is useful when you need to know the position of each element or when you need to iterate a specific number of times. The for-in loop is simpler and more readable when you just need to process each element of a collection without caring about the index.

When should I use `while` vs `do-while`?

Use while when the condition is checked before the first iteration – the loop body may never execute. Use do-while when you need the loop body to execute at least once, regardless of the condition. In a do-while, the condition is checked after the first iteration.

Can I use `break` and `continue` in all loops?

Yes, break and continue work in for, for-in, while, and do-while loops. break exits the loop entirely, while continue skips the rest of the current iteration and proceeds to the next one.

What are labeled loops and when are they useful?

Labeled loops allow you to name a loop and then use break or continue with that label to control which nested loop is affected. This is especially useful when you have nested loops and need to break out of an outer loop from inside an inner loop.

How do I iterate over a map using a loop?

You can iterate over a map using its forEach method: map.forEach((key, value) { ... });. Alternatively, you can loop over map.keys or map.entries and then access the values.

What's the difference between `forEach` and a regular loop?

forEach is a method on iterable collections that applies a function to each element. It's more functional and concise, but you cannot use break or continue inside it, and it doesn't provide an index. Regular loops give you more control (index, break/continue).

Can I create an infinite loop in Dart?

Yes, you can create an infinite loop with while (true) { ... } or for (;;) { ... }. Be careful to include a condition that eventually exits the loop (using break) to avoid freezing your program.

How do I loop through a list with index using a `for-in` loop?

for-in doesn't directly provide an index. To get both index and element, you can use asMap(): for (var entry in list.asMap().entries) { var index = entry.key; var value = entry.value; }. Or stick with a traditional for loop.

Previous

dart conditions

Next

dart functions

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.