HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to DartVariablesData TypesOperatorsStringsListsConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 List & Map
🔀 Condition & Loop
🧩 Function
Dart›Loops (for / while)

Loops (for / while)

Counting with for, iterating over lists with for-in, conditional repetition with while.

Simple enough for a 5-year-old to understand

for loop

Example code
1
void main() {
2
for (var i = 1; i <= 3; i++) {
from 1 to 3 (inclusive).
Loopfrom 1 to 3 (inclusive).
3
print(i);
Prints 1, 2, 3.
Output / InputPrints 1, 2, 3.
4
}
5
}
LoopOutput / Input
💡 Hint: i++ increases i by 1 in each iteration.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

There are four loop structures in Dart: the counted for loop, the collection-traversing for-in loop, the conditional while loop, and the do-while loop which runs at least once. Which one you choose depends on your data and whether you know how many iterations there will be.

If you are iterating over all elements of a collection, for-in is almost always the right choice: you don't manage indices, so you eliminate the possibility of an out-of-bounds error.

Collection methods can also replace loops. Code written with forEach, map, and where is often shorter and its intent is clearer; however, you cannot break out of these methods, which influences your choice.

What you will learn

  • Loop structures and their differences
  • Safe traversal with for-in
  • Using break and continue
  • Avoiding infinite loops
  • The role of collection methods

Who is this for?

  • Learners of repetitive operations
  • Those getting bounds errors in loops
  • Those transitioning to collection methods

When to use?

Use a for loop if the number of iterations is known or if you are traversing a collection.

If the number of iterations is not known beforehand, while is suitable, and if the body needs to run at least once, do-while is appropriate.

Common mistakes

Wrong

void main() {
  var i = 0;
  while (i < 5) {
    print(i);
  }
}

Since the counter is not incremented, the condition remains true forever and the program never ends. You must ensure progress in while loops; this is why the counted for loop is safer.

Correct

void main() {
  var i = 0;
  while (i < 5) {
    print(i);
    i++;
  }
}

Wrong

void main() {
  var liste = [1, 2, 3];
  liste.forEach((e) {
    if (e == 2) break;
    print(e);
  });
}

forEach calls a function, it is not a loop; you cannot break out of it and you will get a "break outside of a loop" error. If you need to terminate the loop early, you should use for-in.

Correct

void main() {
  var liste = [1, 2, 3];
  for (var e in liste) {
    if (e == 2) break;
    print(e);
  }
}

Wrong

void main() {
  for (var i = 0; i < 5; i--) {
    print(i);
  }
}

Because the counter decreases instead of increasing, the condition is never broken and the loop runs forever. Mixing up increment and decrement operators is a common mistake, especially in copied code, and makes the program appear frozen.

Correct

void main() {
  for (var i = 0; i < 5; i++) {
    print(i);
  }
}

Frequently asked questions

Which one should I choose between for-in and forEach?

If you need to exit the loop early, use for-in; if you are simply applying an operation to every element, either one works. for-in is generally more readable and easier to debug.

How do I access both the index and the element at the same time?

You can convert the list to an index-value map using asMap or use a counted for loop. In Flutter code, a counted for loop is still the most common and clear way when an index is needed.

When is do-while used?

When the body needs to run at least once. Since the condition is checked at the end, the first iteration always runs; the typical example is a scenario of asking for input until a valid one is received from the user.

Summary

for-in traverses collections without managing indices.

You must ensure progress in a while loop.

You cannot use break inside forEach.

A counter in the wrong direction produces an infinite loop.

do-while runs the body at least once.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code