Explain it simply
Explain it simply
This lesson teaches no new syntax. It is a workout for what the fundamentals chapters already covered: variables, types, operators, functions, if/else, loops, lists and maps. The four tasks are small on purpose, and each one mixes several ideas so you practise combining them, which is the real skill.
Work like this. Read a task, write your own solution in a file, predict the output before running it, run it with dart run, and only then open the reference solution. Type the code by hand instead of pasting it. The mistakes you find yourself are the ones you remember.
Problem → Why → Solution
The problem: a first draft that only works for the sample
The first version of an exercise usually works for the sample in the task and nothing else. Two classic slips come from habits formed in other languages. A Map looks like a collection, so people write for (final s in scores) and expect pairs. And people expect 9 / 5 on two ints to be integer division, so they store the result in an int variable.
Dart rejects both at compile time, which is helpful, but the messages can look confusing the first time you see them. The draft below contains one of each.
void main() {
final scores = {'Aung': 45, 'Su': 78, 'Kyaw': 50};
for (final entry in scores) { // error: a Map is not Iterable
print(entry);
}
int celsius = 30;
int f = celsius * 9 / 5 + 32; // error: "/" returns a double
print(f);
}What the compiler is telling you
The first error says a Map is not an Iterable: it holds pairs, so Dart makes you choose whether you want the pairs (entries), the keys or the values. The second says a double cannot be stored in an int variable. In Dart the / operator always produces a double, even for two ints, and ~/ is the operator for whole-number division. Neither message points at a mistake in your logic; both are the type system asking you to say what you mean.
Core concept: from the task description to a checked solution
A good exercise solution is built in the same order every time. Following that order keeps the work small and makes the edge cases hard to forget.
1. Write the signature first
Decide the function name, parameters and return type before the body. introduce takes a String, an int, a double and a bool and returns a String; evensUpTo takes a limit and returns a List<int>. If you cannot write the signature, you have not understood the task yet.
2. List the edge cases
Ask what the smallest, emptiest and strangest inputs are: a limit of 0 or a negative one, an empty map, a score of exactly 50, a student with no score yet. Write them as comments or as extra calls in main before you write the body.
3. Choose the loop
Use a counting loop when you need the numbers themselves, for-in over a List or Set when you need each element, and entries, keys or values for a Map. Give the loop variable a name that says what it is, such as entry or n.
4. Return values, print in main
Functions that return a List or a Map can be checked by comparing results; functions that print can only be checked by eye. Do the work in the function and let main show it.
5. Predict, run, compare
Write the output you expect, run the program, and investigate every difference. A surprise is information, not an annoyance.
| Data you have | How to loop over it |
|---|---|
| A range of numbers | for (var n = 1; n <= limit; n++) |
| A List or Set | for (final item in items) |
| A Map, pairs | for (final entry in map.entries) |
| A Map, keys only | for (final key in map.keys) |
| A Map, values only | for (final value in map.values) |
| Expression | Result |
|---|---|
| 9 / 5 | 1.8 (a double) |
| 9 ~/ 5 | 1 (an int, fraction dropped) |
| 9 % 5 | 4 (the remainder) |
- Read the spec, write the signature
- List edge cases as extra calls
- Write the body with the right loop
- Predict the output, then run
- Explain every difference
If a step fails, go back one step, not to the beginning: wrong output usually means a missing edge case, not a wrong signature.
General pattern
ReturnType name(ParamType input) {
final result = <ElementType>[];
for (final item in input) {
if (condition) {
result.add(item);
}
}
return result;
}Take a collection, start with an empty result list, test each element and add only the ones that match. If the input is empty the loop never runs and an empty list comes back.
Reference solutions for the four tasks
Compare these solutions with your own only after you have tried. They go beyond the sample inputs: celsiusToFahrenheit is called with a negative and a zero input, evensUpTo with a limit of 1 and a negative limit, and gradeAll with a score of exactly 50, a null score and an empty map. One line prints 97.88000000000001 on purpose; the floating-point section below explains why.
// Task 1: variables of all four types, joined with string interpolation.
String introduce(String name, int age, double height, bool isStudent) {
final status = isStudent ? 'a student' : 'not a student';
return '$name is $age years old, ${height.toStringAsFixed(2)} m tall, $status.';
}
// Task 2: temperature conversion. "/" always produces a double in Dart.
double celsiusToFahrenheit(double c) => c * 9 / 5 + 32;
// Task 3: even numbers from 1 to limit (an empty list when limit < 2).
List<int> evensUpTo(int limit) {
final evens = <int>[];
for (var n = 1; n <= limit; n++) {
if (n % 2 == 0) evens.add(n);
}
return evens;
}
// Task 4: Pass/Fail per student; a null score means "not marked yet".
Map<String, String> gradeAll(Map<String, int?> scores) {
final results = <String, String>{};
for (final entry in scores.entries) {
final score = entry.value;
if (score == null) {
results[entry.key] = 'No score';
} else if (score >= 50) {
results[entry.key] = 'Pass';
} else {
results[entry.key] = 'Fail';
}
}
return results;
}
void main() {
print(introduce('Aye', 21, 1.65, true));
print(introduce('Zaw', 34, 1.8, false));
for (final c in [30.0, 0.0, -40.0, 37.0]) {
final f = celsiusToFahrenheit(c);
print('${c.toStringAsFixed(1)} C = ${f.toStringAsFixed(1)} F');
}
print(celsiusToFahrenheit(36.6));
print(evensUpTo(20));
print(evensUpTo(1));
print(evensUpTo(-5));
final scores = <String, int?>{
'Aung': 45,
'Su': 78,
'Mya': 60,
'Kyaw': 50,
'Nandar': null,
};
gradeAll(scores).forEach((name, result) => print('$name: $result'));
print(gradeAll({}));
print(scores['Zaw'] ?? 'unknown student');
}Code breakdown
- Interpolation and formatting
return '$name is $age years old, ${height.toStringAsFixed(2)} m tall, $status.';Interpolation inserts values into a String: $name for a simple variable and ${...} for an expression. toStringAsFixed(2) keeps two decimals, which is why 1.8 prints as 1.80.
- Division returns a double
double celsiusToFahrenheit(double c) => c * 9 / 5 + 32;9 / 5 is 1.8, not 1, because / always yields a double in Dart. The arrow => is shorthand for a body that returns one expression. For -40 the formula returns -40.0, a handy check because the two scales meet there.
- A floating-point surprise
print(celsiusToFahrenheit(36.6));The mathematically exact answer is 97.88, but binary doubles cannot store 36.6 exactly, so the printed result is 97.88000000000001. Format for display, and never compare doubles with ==.
- Even numbers
if (n % 2 == 0) evens.add(n);% gives the remainder, so n % 2 == 0 is true for even numbers. An if with a single statement can drop the braces. With a limit of 1 or a negative limit the loop body never runs and an empty list comes back, which is the correct answer, not a bug.
- Loop over entries
for (final entry in scores.entries) {A Map is not Iterable, but its entries are, and each entry has a key and a value. Use .keys or .values when you only need one side.
- A nullable value
final score = entry.value;The map type is Map<String, int?>, so entry.value is an int?. Copying it into a local final variable lets the compiler promote it to int inside the else-if branches once the null check has passed.
- A missing key
print(scores['Zaw'] ?? 'unknown student');Looking up a key that is not in the map returns null, so the result is a nullable type. The ?? operator supplies a fallback instead of crashing.
Aye is 21 years old, 1.65 m tall, a student.
Zaw is 34 years old, 1.80 m tall, not a student.
30.0 C = 86.0 F
0.0 C = 32.0 F
-40.0 C = -40.0 F
37.0 C = 98.6 F
97.88000000000001
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[]
[]
Aung: Fail
Su: Pass
Mya: Pass
Kyaw: Pass
Nandar: No score
{}
unknown studentFloating-point surprises
Doubles store decimal numbers in binary, so values like 0.1 and 0.2 do not exist exactly. That is why 0.1 + 0.2 is not equal to 0.3. This is not a Dart bug but the behaviour of every language that has doubles. The snippet below shows it and two ways to cope: compare with a small tolerance, or format for display. Notice too that ~/ truncates toward zero, so -9 ~/ 5 is -1.
void main() {
final sum = 0.1 + 0.2;
print(sum);
print(sum == 0.3);
print((sum - 0.3).abs() < 1e-9);
print(sum.toStringAsFixed(2));
print(celsiusToFahrenheit(36.6) == 97.88);
print(9 / 5);
print(9 ~/ 5);
print(-9 ~/ 5);
print(9 % 5);
}
double celsiusToFahrenheit(double c) => c * 9 / 5 + 32;More drills
After the four tasks, try these drills with the same routine. The edge cases are the main part: if you forget to test them, the function will look right while being wrong. One word-frequency solution is shown below; notice how the tie-break inside the comparator keeps the output stable when counts are equal.
| Drill | Edge cases to test | Hint |
|---|---|---|
| Word frequency | Empty text, punctuation, equal counts | Split on non-letters, count in a Map, sort by count then word |
| FizzBuzz 1 to n | n = 0, n = 15, negative n | Test % 15 first, then % 3, then % 5 |
| Palindrome check | Empty string, capitals, spaces | Lowercase, keep letters only, compare with the reversed string |
| Second largest score | One score, all equal, empty list | Return int? and sort a copy |
Map<String, int> wordCounts(String text) {
final counts = <String, int>{};
for (final word in text.toLowerCase().split(RegExp(r'[^a-z0-9]+'))) {
if (word.isEmpty) continue;
counts[word] = (counts[word] ?? 0) + 1;
}
return counts;
}
void main() {
final counts = wordCounts('The cat and the hat. The END, and the end!');
final ordered = counts.entries.toList()
..sort((a, b) {
final byCount = b.value.compareTo(a.value);
return byCount != 0 ? byCount : a.key.compareTo(b.key);
});
for (final entry in ordered) {
print('${entry.key}: ${entry.value}');
}
print(wordCounts(' ... '));
print(wordCounts(''));
}In real projects
In real projects
Almost every business script is one of these four tasks in different clothes. Formatting a sentence from fields is what an invoice or a notification does. A conversion function such as Celsius to Fahrenheit has the same shape as currency, unit or timezone conversion. Collecting the items that match a rule is a filter, the heart of search and reporting. And checking each entry of a map against a threshold is how pass/fail, in-stock and over-budget flags are computed.
What changes in real code is the amount of care around the edges. Real input has missing values, empty lists and numbers that sit exactly on a boundary, so production code looks like the reference solutions here rather than the first draft. Reviewers ask 'what happens with an empty list?' and 'what happens at exactly 50?' on almost every pull request.
Common mistakes
Common mistakes
Looping over the Map itself
With for (final s in scores) the compiler says: The type 'Map<String, int>' used in the 'for' loop must implement 'Iterable<dynamic>'. The fix is to loop over .entries, .keys or .values.
Passing an int variable to a double parameter
With int temp = 30; and a call celsiusToFahrenheit(temp) you get: The argument type 'int' can't be assigned to the parameter type 'double'. The literal 30 works because Dart reads it as a double in that position, but a variable keeps its int type. Convert it with temp.toDouble() or declare the variable as a double.
Being off by one at the boundary
Writing score > 50 instead of score >= 50 turns Kyaw's score of exactly 50 into a Fail. Read the task wording ('50 and above') and test the boundary value itself, one value below it and one above it.
Forgetting the null case
With Map<String, int?> the line if (entry.value >= 50) is a compile error: Operator '>=' cannot be called on 'int?' because it is potentially null. Check for null first, or give the missing score a meaning such as 'No score'.
Mini challenge
Class statistics: ties and empty input
Write classStats. It takes a Map of student to score, counts only scores between 0 and 100, and returns a record with the count, the average, the highest score and every student tied for it (alphabetically). Return null when no valid score is left. Then write a report function that prints the result.
- classStats takes a Map<String, int> and returns a nullable record with count, average, highest and leaders
- Scores outside 0..100 are ignored, and null is returned when no valid score remains
- Every student tied for the highest score goes into leaders, sorted alphabetically
- report prints no valid scores for null and a single summary line otherwise
typedef ClassStats = ({int count, double average, int highest, List<String> leaders});
ClassStats? classStats(Map<String, int> scores) {
// TODO: ignore scores outside 0..100
// TODO: return null when no valid score is left
// TODO: count, average, highest score and ALL students tied for highest
// (leaders sorted alphabetically)
}
void report(String label, Map<String, int> scores) {
// TODO: print "<label>: valid=<n>, average=<x.y>, highest=<h> by <A & B>"
// or "<label>: no valid scores" when classStats returns null
}
void main() {
report('Group A', {'Aung': 45, 'Su': 90, 'Mya': 60, 'Zaw': 90, 'Kyaw': 50});
report('Group B', {'Nandar': 101, 'Hla': -4});
report('Group C', {});
report('Group D', {'Solo': 0});
}Expected: Group A gives valid=5, average=67.0, highest=90 by Su & Zaw; Group B and Group C give no valid scores; Group D gives valid=1, average=0.0, highest=0 by Solo.
Show hint
A collection-for with an if can filter while it builds a new map. Divide with / (it gives a double) and call sort() on the leaders list. Check whether the valid map is empty before dividing.
Show solution
typedef ClassStats = ({int count, double average, int highest, List<String> leaders});
/// Statistics for the valid scores (0-100), or null when there are none.
ClassStats? classStats(Map<String, int> scores) {
final valid = {
for (final entry in scores.entries)
if (entry.value >= 0 && entry.value <= 100) entry.key: entry.value,
};
if (valid.isEmpty) return null;
var sum = 0;
var highest = valid.values.first;
for (final score in valid.values) {
sum += score;
if (score > highest) highest = score;
}
final leaders = [
for (final entry in valid.entries)
if (entry.value == highest) entry.key,
]..sort();
return (
count: valid.length,
average: sum / valid.length,
highest: highest,
leaders: leaders,
);
}
void report(String label, Map<String, int> scores) {
final stats = classStats(scores);
if (stats == null) {
print('$label: no valid scores');
return;
}
final avg = stats.average.toStringAsFixed(1);
print('$label: valid=${stats.count}, average=$avg, '
'highest=${stats.highest} by ${stats.leaders.join(' & ')}');
}
void main() {
report('Group A', {'Aung': 45, 'Su': 90, 'Mya': 60, 'Zaw': 90, 'Kyaw': 50});
report('Group B', {'Nandar': 101, 'Hla': -4});
report('Group C', {});
report('Group D', {'Solo': 0});
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Build an exercise in order: signature, edge cases, body, then predict and run
- In Dart / always returns a double and ~/ is whole-number division; never compare doubles with ==
- Loop a Map with entries, keys or values, and remember that a key lookup returns a nullable value
- Do not call a solution done until empty input, boundary values and null have been tried
Dart language overview — Dart