Watch the video (8 min)
On this page23 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is a for-in Loop?
  5. 2. A Group of Values in Square Brackets
  6. 3. The for-in Syntax
  7. 4. Naming the Loop Variable
  8. 5. var, final, or an Explicit Type
  9. 6. Building a Running Total
  10. 7. Decisions Inside the Loop
  11. 8. Looping Over the Characters of a String
  12. 9. An Empty Group Runs Zero Times
  13. 10. for or for-in?
  14. 11. A Real-World Example
  15. Code Examples
  16. Common Beginner Mistakes
  17. Best Practices
  18. Mini Challenge
  19. Practice Questions
  20. Practice Answers
  21. Quick Revision
  22. Key Takeaways
  23. What's Next?

Lecture 27 — for-in Loops

Category5 — Control Flow
Lecture027 of 140
Estimated video length8 min
TargetDart 3.12.2
LevelBeginner

A counting for loop makes you manage a counter, a limit and a position. When you just want each value in a group, a for-in loop hands you the values one by one.

Contents

Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways

Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.


Prerequisites

Students should already understand, from Lectures 004–026:

  • var, final, and string interpolation
  • string indexes and length (Lecture 008)
  • compound assignment such as += (Lecture 017)
  • if statements (Lecture 022)
  • the counting for loop (Lecture 026)

Connection With Previous Lectures

In Lecture 026, we printed each letter of a word with a counting loop:

dart
void main() {
  var word = 'Ali';
  for (var i = 0; i < word.length; i++) {
    print(word[i]);
  }
}
output
A
l
i

It works, but look at what we had to manage: a counter i, a start value, a limit, a step, and word[i] to fetch each letter. Write <= instead of < and the program crashes. Most of the time we don't care about positions at all — we just want each value, in order.


Learning Objectives

By the end of this lecture you will be able to:

  • Write a group of values in square brackets and store it in a variable
  • Write a for-in loop that visits every value in a group
  • Choose a clear, singular name for the loop variable
  • Use var, final, or an explicit type for the loop variable
  • Combine a for-in loop with += and if to total and count values
  • Loop over the characters of a string with split('')
  • Choose between a counting for loop and a for-in loop
  • Recognize the error messages Dart produces for common for-in mistakes

1. What Is a for-in Loop?

A for-in loop runs its body once for each value in a group, giving you that value under a name you choose.

Analogy — think of a teacher handing back exam papers. She doesn't count "paper 0, paper 1, paper 2". She picks up the next paper, deals with it, and moves on until the pile is empty.


2. A Group of Values in Square Brackets

To loop over values, we need a group of them. Write the values inside square brackets, separated by commas:

dart
void main() {
  var marks = [85, 92, 78];
  print(marks);
}
output
[85, 92, 78]

You met this briefly in Lecture 007: Dart calls such a group a List. For this lecture, that is all you need — a group of values, in order, stored in one variable. Everything else about lists — reading one value, adding and removing values, sorting — starts in Lecture 039.


3. The for-in Syntax

dart
void main() {
  var marks = [85, 92, 78];
  for (var mark in marks) {
    print(mark);
  }
}
output
85
92
78

Read it aloud: "for each mark in marks, print mark". On the first pass mark is 85, then 92, then 78. When the group runs out, the loop ends. No counter, no limit, no index.


4. Naming the Loop Variable

The group gets a plural name, and the loop variable the singular: marks → mark, names → name, prices → price.

dart
void main() {
  var names = ['Ali', 'Sara', 'Zayan'];
  for (var name in names) {
    print('Hello, $name!');
  }
}
output
Hello, Ali!
Hello, Sara!
Hello, Zayan!

for (var x in names) would also run, but name tells the reader what each value is.


5. var, final, or an Explicit Type

Dart infers the loop variable's type from the group, just like var in Lecture 005. Since the loop body usually only reads the value, final is a good choice:

dart
void main() {
  var prices = [4.5, 12.0, 3.25];
  for (final price in prices) {
    print('Price: $price');
  }
  for (double price in prices) {
    print('Double it: ${price * 2}');
  }
}
output
Price: 4.5
Price: 12.0
Price: 3.25
Double it: 9.0
Double it: 24.0
Double it: 6.5

final is new for every pass, so it gets a fresh value each time — it only stops you from changing it inside one pass. An explicit type must match the values, or Dart refuses to compile (see Common Mistakes).


6. Building a Running Total

Combine for-in with += from Lecture 017. Start a total at 0 before the loop, add to it inside, and print it after:

dart
void main() {
  var marks = [85, 92, 78];
  var total = 0;
  for (final mark in marks) {
    total += mark;
  }
  print('Total: $total');
}
output
Total: 255

The pattern "start before, update inside, use after" appears in almost every loop you will write.


7. Decisions Inside the Loop

The body can hold any statements, including an if from Lecture 022:

dart
void main() {
  var marks = [85, 42, 78, 39];
  var passed = 0;
  for (final mark in marks) {
    if (mark >= 50) {
      passed++;
    }
  }
  print('Passed: $passed of 4');
}
output
Passed: 2 of 4

The if runs once per value, so each mark gets its own check.


8. Looping Over the Characters of a String

A string is not a group Dart can loop over directly — for (var letter in 'Ali') is an error (see Common Mistakes). The method split('') breaks a string into a group of one-character strings:

dart
void main() {
  print('Sara'.split(''));
  for (final letter in 'Sara'.split('')) {
    print(letter);
  }
}
output
[S, a, r, a]
S
a
r
a

Compare this with the counting loop in the Connection section: same result, nothing to count. split can also break text at spaces or commas; we return to it with lists.


9. An Empty Group Runs Zero Times

If the group has no values, the body simply never runs. Splitting an empty string gives an empty group:

dart
void main() {
  print(''.split(''));
  for (final letter in ''.split('')) {
    print('Letter: $letter');
  }
  print('Done');
}
output
[]
Done

No crash and no special check needed.


10. for or for-in?

You need…Use
each value, in orderfor-in
a number that counts (1 to 10, a times table)counting for
the position of each valuecounting for
dart
void main() {
  var word = 'Zayan';
  for (var i = 0; i < word.length; i++) {
    print('$i: ${word[i]}');
  }
}
output
0: Z
1: a
2: y
3: a
4: n

A for-in loop gives you values, not positions, so here the counting loop is right.


11. A Real-World Example

Ali's shopping basket: total the prices and count the items that cost more than 10.

dart
void main() {
  var prices = [4.5, 12.0, 3.25, 18.75];
  var total = 0.0;
  var expensive = 0;

  for (final price in prices) {
    total += price;
    if (price > 10) {
      expensive++;
    }
  }

  print('Total: ${total.toStringAsFixed(2)}');
  print('Items over 10: $expensive');
}
output
Total: 38.50
Items over 10: 2

total starts as 0.0 so it is a double and can hold decimal prices — the 25 vs 25.0 lesson from Lecture 005.


Code Examples

Example 1 — Printing Every Value

dart
void main() {
  var scores = [10, 20, 30];
  for (final score in scores) {
    print(score);
  }
}
output
10
20
30

Example 2 — Strings in a Group

dart
void main() {
  var cities = ['Lahore', 'Karachi', 'Islamabad'];
  for (final city in cities) {
    print('Visit $city');
  }
}
output
Visit Lahore
Visit Karachi
Visit Islamabad

Example 3 — An Explicit Type

dart
void main() {
  var ages = [6, 18, 20];
  for (int age in ages) {
    print('Next year: ${age + 1}');
  }
}
output
Next year: 7
Next year: 19
Next year: 21

Example 4 — Letters of a Word

dart
void main() {
  for (final letter in 'Dart'.split('')) {
    print(letter.toUpperCase());
  }
}
output
D
A
R
T

Example 5 — Counting Matches

dart
void main() {
  var count = 0;
  for (final letter in 'banana'.split('')) {
    if (letter == 'a') {
      count++;
    }
  }
  print('a appears $count times');
}
output
a appears 3 times

Example 6 — Building a String

dart
void main() {
  var names = ['Ali', 'Sara', 'Zayan'];
  var initials = '';
  for (final name in names) {
    initials += name[0];
  }
  print(initials);
}
output
ASZ

name[0] is the string index from Lecture 008, applied to each name.

Example 7 — Student Average

dart
void main() {
  var marks = [80, 75, 85, 90];
  var total = 0;
  var count = 0;
  for (final mark in marks) {
    total += mark;
    count++;
  }
  print('Total: $total');
  print('Average: ${total / count}');
}
output
Total: 330
Average: 82.5

count grows by one per pass, so it ends as the number of marks. / always gives a double, so the average keeps its decimal part.

Example 8 — Shopping Total with Discount

dart
void main() {
  var prices = [1200, 450, 800];
  var subtotal = 0;
  for (final price in prices) {
    subtotal += price;
  }
  var total = subtotal >= 2000 ? subtotal * 0.9 : subtotal * 1.0;
  print('Subtotal: $subtotal');
  print('Total: $total');
}
output
Subtotal: 2450
Total: 2205.0

The loop builds the subtotal; the conditional expression from Lecture 020 applies the 10% discount once, after the loop.

Example 9 — Bank Balance

dart
void main() {
  var balance = 1000;
  var changes = [250, -400, 75, -100];
  for (final change in changes) {
    balance += change;
    print('Balance: $balance');
  }
}
output
Balance: 1250
Balance: 850
Balance: 925
Balance: 825

Deposits are positive, withdrawals negative, so += handles both.

Example 10 — Highest Temperature

dart
void main() {
  var temperatures = [21.5, 25.0, 19.0, 27.5, 24.0];
  var highest = temperatures[0];
  for (final temperature in temperatures) {
    if (temperature > highest) {
      highest = temperature;
    }
  }
  print('Highest: $highest');
}
output
Highest: 27.5

highest starts as the first value (temperatures[0] — indexes work the same as in strings; Lecture 040 covers them for lists). Each larger value replaces it.


Common Beginner Mistakes

1. Looping over a string directly

dart
void main() {
  var word = 'Ali';
  // for (var letter in word) { // ✗
  //   print(letter);
  // }
}
output
Error: The type 'String' used in the 'for' loop must implement 'Iterable<dynamic>'.

"Iterable" means "something a loop can walk through". A string isn't one — loop over word.split('') instead.

2. A loop variable type that doesn't match the values

dart
void main() {
  var marks = [85, 92, 78];
  // for (String mark in marks) { // ✗ the values are int
  //   print(mark);
  // }
}
output
Error: A value of type 'int' can't be assigned to a variable of type 'String'.

Use int, or let Dart infer it with var or final.

3. Using the loop variable after the loop

dart
void main() {
  var marks = [85, 92, 78];
  for (var mark in marks) {
    print(mark);
  }
  // print(mark); // ✗ mark exists only inside the loop
}
output
Error: Undefined name 'mark'.

To keep a result, store it in a variable declared before the loop, like total.

4. Changing a final loop variable

dart
void main() {
  var marks = [85, 92, 78];
  for (final mark in marks) {
    // mark = mark + 5; // ✗
    print(mark + 5);
  }
}
output
Error: Can't assign to the final variable 'mark'.

Use the new value directly (mark + 5) or store it in another variable.

5. Expecting the group to change

With var mark, mark = mark + 5 compiles — but it changes only the loop variable, never the group:

dart
void main() {
  var marks = [85, 92, 78];
  for (var mark in marks) {
    mark = mark + 5;
  }
  print(marks);
}
output
[85, 92, 78]

Changing the values inside a list is covered in Lectures 040–043.

6. Starting the total inside the loop

If var total = 0; is written inside the body, it is reset on every pass. Declare it before the loop.

7. Writing of instead of in

Some languages write for (x of items). Dart only accepts in; of produces a long chain of confusing errors.


Best Practices

  • Use for-in when you need each value; use a counting for when you need numbers or positions.
  • Name the group in the plural and the loop variable in the singular.
  • Prefer final for the loop variable when the body only reads it.
  • Declare totals and counters before the loop, update them inside, use them after.
  • Keep the body short — one clear job per loop.

Mini Challenge

Sara's quiz scores are 7, 9, 4, 10, and 6. Print each score with a label — Good for 7 or more, Practice otherwise — then print the total.

output
7: Good
9: Good
4: Practice
10: Good
6: Practice
Total: 36

Try it yourself before opening the solution.

Show solution
dart
void main() {
  var scores = [7, 9, 4, 10, 6];
  var total = 0;
  for (final score in scores) {
    var label = score >= 7 ? 'Good' : 'Practice';
    print('$score: $label');
    total += score;
  }
  print('Total: $total');
}
output
7: Good
9: Good
4: Practice
10: Good
6: Practice
Total: 36

Practice Questions

Work through these in order — they run from beginner to application to challenge.

Beginner

  1. Store ['red', 'green', 'blue'] in colors and print each colour on its own line.
  2. Store [3, 6, 9] and print each number multiplied by 10.
  3. Print each letter of 'Zayan' on its own line using a for-in loop.

Application

  1. Store the prices [250, 100, 650] and print their total as Total: ….
  2. Store [12, 7, 30, 15, 4] and count how many numbers are greater than 10.
  3. Count the vowels (a, e, i, o, u) in 'education'.
  4. Store ['Ali', 'Sara', 'Zayan'] and print Ali has 3 letters, and so on, using length.
  5. Store the temperatures [18.5, 22.0, 25.5] in Celsius and print each in Fahrenheit (c * 9 / 5 + 32).

Challenge

  1. Store [64, 89, 47, 95, 72] and print the lowest mark.
  2. Reverse the word 'Dart' with a for-in loop, so the program prints traD. Hint: add each letter to the front of a result string.

Practice Answers

Question 1 — Solution

dart
void main() {
  var colors = ['red', 'green', 'blue'];
  for (final color in colors) {
    print(color);
  }
}
output
red
green
blue

Question 2 — Solution

dart
void main() {
  var numbers = [3, 6, 9];
  for (final number in numbers) {
    print(number * 10);
  }
}
output
30
60
90

Question 3 — Solution

dart
void main() {
  for (final letter in 'Zayan'.split('')) {
    print(letter);
  }
}
output
Z
a
y
a
n

Question 4 — Solution

dart
void main() {
  var prices = [250, 100, 650];
  var total = 0;
  for (final price in prices) {
    total += price;
  }
  print('Total: $total');
}
output
Total: 1000

Question 5 — Solution

dart
void main() {
  var numbers = [12, 7, 30, 15, 4];
  var count = 0;
  for (final number in numbers) {
    if (number > 10) {
      count++;
    }
  }
  print(count);
}
output
3

Question 6 — Solution

dart
void main() {
  var vowels = 0;
  for (final letter in 'education'.split('')) {
    if ('aeiou'.contains(letter)) {
      vowels++;
    }
  }
  print('Vowels: $vowels');
}
output
Vowels: 5

contains from Lecture 008 checks whether the letter appears in 'aeiou'.

Question 7 — Solution

dart
void main() {
  var names = ['Ali', 'Sara', 'Zayan'];
  for (final name in names) {
    print('$name has ${name.length} letters');
  }
}
output
Ali has 3 letters
Sara has 4 letters
Zayan has 5 letters

Question 8 — Solution

dart
void main() {
  var temperatures = [18.5, 22.0, 25.5];
  for (final c in temperatures) {
    print('$c°C = ${c * 9 / 5 + 32}°F');
  }
}
output
18.5°C = 65.3°F
22.0°C = 71.6°F
25.5°C = 77.9°F

Question 9 — Solution

dart
void main() {
  var marks = [64, 89, 47, 95, 72];
  var lowest = marks[0];
  for (final mark in marks) {
    if (mark < lowest) {
      lowest = mark;
    }
  }
  print('Lowest: $lowest');
}
output
Lowest: 47

Question 10 — Solution

dart
void main() {
  var reversed = '';
  for (final letter in 'Dart'.split('')) {
    reversed = letter + reversed;
  }
  print(reversed);
}
output
traD

Each new letter goes in front: D → aD → raD → traD.


Quick Revision

  1. What does a for-in loop give you on each pass?
  2. How do you write a group of three numbers in Dart?
  3. Why is for (var letter in 'Ali') an error, and what is the fix?
  4. Why is final a good choice for the loop variable?
  5. Where should a running total be declared?
  6. What happens when the group is empty?
  7. When should you use a counting for loop instead?

Key Takeaways

  • A for-in loop runs its body once for each value in a group, in order.
  • Values in square brackets, like [85, 92, 78], form a group Dart calls a List.
  • The syntax is for (final item in items) { … } — plural group, singular loop variable.
  • The loop variable can be var, final, or an explicit type that matches the values.
  • The loop variable exists only inside the loop; changing it never changes the group.
  • A string is not loopable directly — use split('') to get its characters.
  • An empty group runs the body zero times.
  • Use for-in for values; use a counting for for numbers and positions.

What's Next?

Lecture 028 — while & do-while. A for-in loop needs a group to walk through, and a counting for loop needs to know how many times to repeat. Sometimes you know neither — "keep going until the balance runs out". while and do-while loops repeat as long as a condition stays true.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.