On this page23 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is a for-in Loop?
- 2. A Group of Values in Square Brackets
- 3. The for-in Syntax
- 4. Naming the Loop Variable
- 5. var, final, or an Explicit Type
- 6. Building a Running Total
- 7. Decisions Inside the Loop
- 8. Looping Over the Characters of a String
- 9. An Empty Group Runs Zero Times
- 10. for or for-in?
- 11. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 27 — for-in Loops
| Category | 5 — Control Flow |
| Lecture | 027 of 140 |
| Estimated video length | 8 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
A counting
forloop makes you manage a counter, a limit and a position. When you just want each value in a group, afor-inloop 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) ifstatements (Lecture 022)- the counting
forloop (Lecture 026)
Connection With Previous Lectures
In Lecture 026, we printed each letter of a word with a counting loop:
void main() {
var word = 'Ali';
for (var i = 0; i < word.length; i++) {
print(word[i]);
}
}A
l
iIt 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-inloop 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-inloop with+=andifto total and count values - Loop over the characters of a string with
split('') - Choose between a counting
forloop and afor-inloop - Recognize the error messages Dart produces for common
for-inmistakes
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:
void main() {
var marks = [85, 92, 78];
print(marks);
}[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
void main() {
var marks = [85, 92, 78];
for (var mark in marks) {
print(mark);
}
}85
92
78Read 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.
void main() {
var names = ['Ali', 'Sara', 'Zayan'];
for (var name in names) {
print('Hello, $name!');
}
}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:
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}');
}
}Price: 4.5
Price: 12.0
Price: 3.25
Double it: 9.0
Double it: 24.0
Double it: 6.5final 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:
void main() {
var marks = [85, 92, 78];
var total = 0;
for (final mark in marks) {
total += mark;
}
print('Total: $total');
}Total: 255The 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:
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');
}Passed: 2 of 4The 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:
void main() {
print('Sara'.split(''));
for (final letter in 'Sara'.split('')) {
print(letter);
}
}[S, a, r, a]
S
a
r
aCompare 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:
void main() {
print(''.split(''));
for (final letter in ''.split('')) {
print('Letter: $letter');
}
print('Done');
}[]
DoneNo crash and no special check needed.
10. for or for-in?
| You need… | Use |
|---|---|
| each value, in order | for-in |
| a number that counts (1 to 10, a times table) | counting for |
| the position of each value | counting for |
void main() {
var word = 'Zayan';
for (var i = 0; i < word.length; i++) {
print('$i: ${word[i]}');
}
}0: Z
1: a
2: y
3: a
4: nA 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.
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');
}Total: 38.50
Items over 10: 2total 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
void main() {
var scores = [10, 20, 30];
for (final score in scores) {
print(score);
}
}10
20
30Example 2 — Strings in a Group
void main() {
var cities = ['Lahore', 'Karachi', 'Islamabad'];
for (final city in cities) {
print('Visit $city');
}
}Visit Lahore
Visit Karachi
Visit IslamabadExample 3 — An Explicit Type
void main() {
var ages = [6, 18, 20];
for (int age in ages) {
print('Next year: ${age + 1}');
}
}Next year: 7
Next year: 19
Next year: 21Example 4 — Letters of a Word
void main() {
for (final letter in 'Dart'.split('')) {
print(letter.toUpperCase());
}
}D
A
R
TExample 5 — Counting Matches
void main() {
var count = 0;
for (final letter in 'banana'.split('')) {
if (letter == 'a') {
count++;
}
}
print('a appears $count times');
}a appears 3 timesExample 6 — Building a String
void main() {
var names = ['Ali', 'Sara', 'Zayan'];
var initials = '';
for (final name in names) {
initials += name[0];
}
print(initials);
}ASZname[0] is the string index from Lecture 008, applied to each name.
Example 7 — Student Average
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}');
}Total: 330
Average: 82.5count 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
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');
}Subtotal: 2450
Total: 2205.0The loop builds the subtotal; the conditional expression from Lecture 020 applies the 10% discount once, after the loop.
Example 9 — Bank Balance
void main() {
var balance = 1000;
var changes = [250, -400, 75, -100];
for (final change in changes) {
balance += change;
print('Balance: $balance');
}
}Balance: 1250
Balance: 850
Balance: 925
Balance: 825Deposits are positive, withdrawals negative, so += handles both.
Example 10 — Highest Temperature
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');
}Highest: 27.5highest 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
void main() {
var word = 'Ali';
// for (var letter in word) { // ✗
// print(letter);
// }
}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
void main() {
var marks = [85, 92, 78];
// for (String mark in marks) { // ✗ the values are int
// print(mark);
// }
}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
void main() {
var marks = [85, 92, 78];
for (var mark in marks) {
print(mark);
}
// print(mark); // ✗ mark exists only inside the loop
}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
void main() {
var marks = [85, 92, 78];
for (final mark in marks) {
// mark = mark + 5; // ✗
print(mark + 5);
}
}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:
void main() {
var marks = [85, 92, 78];
for (var mark in marks) {
mark = mark + 5;
}
print(marks);
}[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-inwhen you need each value; use a countingforwhen you need numbers or positions. - Name the group in the plural and the loop variable in the singular.
- Prefer
finalfor 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.
7: Good
9: Good
4: Practice
10: Good
6: Practice
Total: 36Try it yourself before opening the solution.
Show solution
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');
}7: Good
9: Good
4: Practice
10: Good
6: Practice
Total: 36Practice Questions
Work through these in order — they run from beginner to application to challenge.
Beginner
- Store
['red', 'green', 'blue']incolorsand print each colour on its own line. - Store
[3, 6, 9]and print each number multiplied by10. - Print each letter of
'Zayan'on its own line using afor-inloop.
Application
- Store the prices
[250, 100, 650]and print their total asTotal: …. - Store
[12, 7, 30, 15, 4]and count how many numbers are greater than10. - Count the vowels (
a,e,i,o,u) in'education'. - Store
['Ali', 'Sara', 'Zayan']and printAli has 3 letters, and so on, usinglength. - Store the temperatures
[18.5, 22.0, 25.5]in Celsius and print each in Fahrenheit (c * 9 / 5 + 32).
Challenge
- Store
[64, 89, 47, 95, 72]and print the lowest mark. - Reverse the word
'Dart'with afor-inloop, so the program printstraD. Hint: add each letter to the front of a result string.
Practice Answers
Question 1 — Solution
void main() {
var colors = ['red', 'green', 'blue'];
for (final color in colors) {
print(color);
}
}red
green
blueQuestion 2 — Solution
void main() {
var numbers = [3, 6, 9];
for (final number in numbers) {
print(number * 10);
}
}30
60
90Question 3 — Solution
void main() {
for (final letter in 'Zayan'.split('')) {
print(letter);
}
}Z
a
y
a
nQuestion 4 — Solution
void main() {
var prices = [250, 100, 650];
var total = 0;
for (final price in prices) {
total += price;
}
print('Total: $total');
}Total: 1000Question 5 — Solution
void main() {
var numbers = [12, 7, 30, 15, 4];
var count = 0;
for (final number in numbers) {
if (number > 10) {
count++;
}
}
print(count);
}3Question 6 — Solution
void main() {
var vowels = 0;
for (final letter in 'education'.split('')) {
if ('aeiou'.contains(letter)) {
vowels++;
}
}
print('Vowels: $vowels');
}Vowels: 5contains from Lecture 008 checks whether the letter appears in 'aeiou'.
Question 7 — Solution
void main() {
var names = ['Ali', 'Sara', 'Zayan'];
for (final name in names) {
print('$name has ${name.length} letters');
}
}Ali has 3 letters
Sara has 4 letters
Zayan has 5 lettersQuestion 8 — Solution
void main() {
var temperatures = [18.5, 22.0, 25.5];
for (final c in temperatures) {
print('$c°C = ${c * 9 / 5 + 32}°F');
}
}18.5°C = 65.3°F
22.0°C = 71.6°F
25.5°C = 77.9°FQuestion 9 — Solution
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');
}Lowest: 47Question 10 — Solution
void main() {
var reversed = '';
for (final letter in 'Dart'.split('')) {
reversed = letter + reversed;
}
print(reversed);
}traDEach new letter goes in front: D → aD → raD → traD.
Quick Revision
- What does a
for-inloop give you on each pass? - How do you write a group of three numbers in Dart?
- Why is
for (var letter in 'Ali')an error, and what is the fix? - Why is
finala good choice for the loop variable? - Where should a running total be declared?
- What happens when the group is empty?
- When should you use a counting
forloop instead?
Key Takeaways
- A
for-inloop 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-infor values; use a countingforfor 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.