Familiar shapes with a few Dart twists
If you have written loops and functions in any C-family language, most of Dart's control flow will look like home: if, for, while, braces, semicolons. This lesson moves quickly through the familiar parts and slows down for the places where Dart differs or where professionals have strong habits: the switch expression, named parameters (which Flutter uses on almost every call), closures and how they capture variables, and Dart's split between exceptions that programs should handle and errors that mean the program has a bug.
Branches and loops
void main() {
// if / else if / else, and the conditional operator.
for (final year in [1900, 2000, 2024, 2026]) {
final leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
final kind = leap ? 'leap' : 'common';
if (year < 2000) {
print('$year was a $kind year');
} else if (year <= 2025) {
print('$year: $kind');
} else {
print('$year will be $kind');
}
}
// A labelled continue skips to the next candidate as soon as a divisor is found.
final primes = <int>[];
candidates:
for (var n = 2; n < 40; n++) {
for (final p in primes) {
if (p * p > n) break;
if (n % p == 0) continue candidates;
}
primes.add(n);
}
print(primes);
// while and do-while.
var n = 9875;
var digitSum = 0;
while (n > 0) {
digitSum += n % 10;
n ~/= 10;
}
var rolls = 0;
do {
rolls++;
} while (rolls * rolls < 30);
print('digit sum $digitSum, rolls $rolls');
// A switch expression maps a value to a result; _ matches anything else.
for (final day in [1, 6, 9]) {
final name = switch (day) {
1 => 'Monday',
6 || 7 => 'weekend',
_ => 'not a day number we know',
};
print('$day: $name');
}
}1900 was a common year
2000: leap
2024: leap
2026 will be common
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
digit sum 29, rolls 6
1: Monday
6: weekend
9: not a day number we know- Conditions must be
bool. Dart does not treat0,''ornullas false:if (count)is a compile error. - Loops. The classic
for (var n = 2; n < 40; n++)exists alongsidefor (final p in primes), which walks anyIterable. Prefer for-in when you need the elements rather than the positions. - Labels.
continue candidatesjumps to the next iteration of the loop labelledcandidates:, skipping the rest of the outer body, so a number with a divisor is never added. A plaincontinuewould only have moved the inner loop on. ~/=is the compound form of integer division; every operator has one (+=,??=,~/=).- The switch expression (Dart 3.0) evaluates to the result of the first matching case, written
pattern => result. Cases can be alternatives joined with||, and_matches anything. A switch expression must be exhaustive: here, without the_case, the compiler would reject it, because aninthas values that no case covers. Switch statements (withcase ...:and nobreakneeded: since Dart 3, a case with a body never falls through into the next) exist too, and the lesson on patterns shows how much more both forms can do.
Functions and their parameters
Dart functions have three kinds of parameters, and choosing well makes call sites readable.
Definition— positional, optional and named parameters
Required positional parameters are listed first and passed in order. Optional positional parameters go in square brackets [ ] and may be omitted from the end. Named parameters go in braces { } and are passed as name: value in any order; they are optional unless marked required. An optional parameter must either be nullable or have a default value.
// Named parameters in braces; `required` ones must be passed.
String describeTrip({
required String from,
required String to,
int stops = 0,
}) => '$from → $to${stops == 0 ? ' (direct)' : ' with $stops stop(s)'}';
// Optional positional parameters in square brackets.
String greet(String name, [String? title]) =>
title == null ? 'Hello, $name' : 'Hello, $title $name';
// A function type, named with typedef.
typedef Rule = bool Function(int);
List<int> keep(List<int> numbers, Rule rule) => [
for (final n in numbers)
if (rule(n)) n,
];
void main() {
print(describeTrip(from: 'Nairobi', to: 'Kigali'));
print(describeTrip(to: 'Accra', from: 'Lagos', stops: 1)); // named: any order
print(greet('Mbeki'));
print(greet('Mbeki', 'Dr'));
final numbers = [3, 8, 12, 15, 22];
bool isEven(int n) => n.isEven; // a local function
print(keep(numbers, isEven));
print(keep(numbers, (n) => n > 10)); // an anonymous function
print(numbers.map((n) => n * n).where((n) => n < 200).toList());
// Tear-offs: use a function or method by name, without calling it.
final shout = (String s) => s.toUpperCase();
print(['jambo', 'salut'].map(shout).toList());
print(['7', '11'].map(int.parse).reduce((a, b) => a + b));
}Nairobi → Kigali (direct)
Lagos → Accra with 1 stop(s)
Hello, Mbeki
Hello, Dr Mbeki
[8, 12, 22]
[12, 15, 22]
[9, 64, 144]
[JAMBO, SALUT]
18describeTrip has two required named parameters and an optional one with a default, so a call names every argument it passes and the order does not matter. This is the dominant style in Flutter, where a widget may take a dozen parameters: Text('Hi', style: ..., maxLines: 2). Positional parameters are best when the meaning is obvious from the function name (greet('Mbeki'), max(a, b)), named parameters when it is not.
Functions are first-class objects. keep takes a function of type bool Function(int), given the name Rule with typedef. You can pass a named local function (isEven), an anonymous function ((n) => n > 10, whose parameter type is inferred from context), or a tear-off: the name of a function or method without parentheses, such as int.parse, used as a value. The function returning a list uses a collection for with an if inside the list literal, which you will meet properly in the next lesson.
map and where return lazy iterables; toList() makes a list. Chains like map(...).where(...) are idiomatic, and Effective Dart prefers them, or collection literals, to manual loops that append to a list.
Closures
A function written inside another can use the outer function's variables, and keeps them alive as long as it exists. Such a function is a closure.
// A closure captures variables, not values.
int Function() makeCounter(int step) {
var count = 0;
return () => count += step;
}
void main() {
final byTwo = makeCounter(2);
final byFive = makeCounter(5);
print('${byTwo()} ${byTwo()} ${byFive()} ${byTwo()}');
// Each iteration of a for loop has its own fresh loop variable.
final callbacks = <String Function()>[];
for (var i = 1; i <= 3; i++) {
callbacks.add(() => 'callback $i');
}
print(callbacks.map((f) => f()).join(', '));
// A variable declared outside the loop is shared by every closure.
var shared = 0;
final readers = <int Function()>[];
for (final step in [10, 20, 30]) {
shared = step;
readers.add(() => shared);
}
print(readers.map((f) => f()).toList());
}2 4 5 6
callback 1, callback 2, callback 3
[30, 30, 30]Each call to makeCounter creates a new count, so byTwo and byFive count independently: byTwo returns 2, 4 and then 6, while byFive's single call returns 5. The return type int Function() reads "a function that takes nothing and returns an int"; the body count += step is an expression whose value is the new count.
The loop example shows a detail that differs between languages. A closure captures variables, not values. In Dart, every iteration of a for loop gets a fresh copy of the loop variable, so the three callbacks see 1, 2 and 3. (Older JavaScript code with var famously printed the last value three times.) But a variable declared outside the loop, like shared, is one variable, and all three closures read its final value, 30. When you create closures in a loop, be sure each one captures what you meant.
Recursion and the call stack
A function may call itself. Each call gets its own frame on the call stack, holding its parameters and local variables, and the frame is released when the call returns. That makes recursion natural for recursive data, such as walking a tree of folders or a nested JSON document, but it also sets a limit: on the machine that checked this course, a function that recursed ten thousand levels deep worked fine, while one that tried a hundred million levels ran out of stack and threw a StackOverflowError. Dart does not promise tail-call elimination (reusing the frame when the recursive call is the last thing a function does), so rewriting a deep recursion in tail form does not help. When the depth depends on input size, such as the length of a list, write a loop, or keep your own stack in a List.
Exceptions and errors
Dart signals failure by throwing an object. Any non-null object can be thrown, but by convention you throw one of two kinds:
- An
Exceptiondescribes a problem that a correct program should expect and handle: bad input, a missing file, a network failure. Define your own by implementingException. - An
Errordescribes a bug in the program: a wrong argument (ArgumentError), an index out of range (RangeError), a failed null assertion. Errors are not meant to be caught in normal code; the fix is to change the program.
class InsufficientFunds implements Exception {
final int shortBy;
InsufficientFunds(this.shortBy);
@override
String toString() => 'InsufficientFunds: short by $shortBy';
}
int withdraw(int balance, int amount) {
if (amount <= 0)
throw ArgumentError.value(amount, 'amount', 'must be positive');
if (amount > balance) throw InsufficientFunds(amount - balance);
return balance - amount;
}
void main() {
for (final amount in [30, 80, -5]) {
try {
final left = withdraw(50, amount);
print('withdrew $amount, $left left');
} on InsufficientFunds catch (e) {
print('declined: ${e.shortBy} short');
} on ArgumentError catch (e) {
print('bug in the caller: ${e.message}');
} finally {
print(' (receipt printed)');
}
}
// parse throws FormatException; tryParse returns null.
try {
int.parse('12a');
} on FormatException catch (e) {
print('FormatException: ${e.message}');
}
print(int.tryParse('12a') ?? 'not a number');
// assert is checked only when asserts are enabled (dart run --enable-asserts).
assert(1 + 1 == 3, 'this message only appears with asserts enabled');
print('asserts are off by default in dart run');
}withdrew 30, 20 left
(receipt printed)
declined: 30 short
(receipt printed)
bug in the caller: must be positive
(receipt printed)
FormatException: Invalid radix-10 number
not a number
asserts are off by default in dart runA try block is followed by on Type catch (e) clauses, tried in order; on without catch handles a type without naming the object, and a bare catch (e) catches anything (add a second parameter, catch (e, stack), to get the stack trace). finally runs whether or not an exception was thrown, so the receipt line appears every time. Inside a catch, rethrow passes the same exception on, keeping its original stack trace.
Notice that Dart functions do not declare which exceptions they throw, and callers are not forced to catch them; unlike Swift's try or Java's checked exceptions, nothing at the call site tells you a call can throw. That makes documentation (/// Throws [FormatException] if ...) and APIs like tryParse, which return null instead of throwing, especially valuable. Effective Dart advises against catching errors and against catch clauses with no on type, which hide bugs along with the problems you meant to handle.
Finally, assert checks a condition during development. dart run runs with assertions disabled (pass --enable-asserts to turn them on), and Flutter enables them in debug builds and removes them from release builds. So an assert documents an assumption and catches mistakes while you work, but must never be the only protection against bad data.
Worked example: validating a check digit
Example— Is this ISBN well formed?
Books carry an ISBN-13, and its last digit is a check digit computed from the other twelve, so that a single mistyped digit (and most swaps of neighbouring digits) can be detected. The rule: multiply the twelve digits alternately by 1 and 3, add the products, and choose the check digit that brings the total up to a multiple of 10. The book numbers below are made up, with check digits computed by the function itself.
/// Returns the check digit for the first 12 digits of an ISBN-13.
///
/// Throws a [FormatException] if [first12] is not exactly 12 digits.
int isbnCheckDigit(String first12) {
if (first12.length != 12 || int.tryParse(first12) == null) {
throw FormatException('expected 12 digits', first12);
}
var sum = 0;
for (var i = 0; i < 12; i++) {
final digit = int.parse(first12[i]);
sum += i.isEven ? digit : 3 * digit; // weights 1, 3, 1, 3, ...
}
return (10 - sum % 10) % 10;
}
/// Checks a whole ISBN-13, ignoring hyphens and spaces.
bool isValidIsbn(String isbn) {
final digits = isbn.replaceAll(RegExp(r'[-\s]'), '');
if (digits.length != 13) return false;
try {
return isbnCheckDigit(digits.substring(0, 12)) == int.parse(digits[12]);
} on FormatException {
return false;
}
}
void main() {
print(isbnCheckDigit('978123456789'));
const candidates = [
'978-1-23456-789-7',
'978-1-23456-789-2',
'978 9966 25 431 3',
'97899662543X3',
'12345',
];
for (final isbn in candidates) {
print('${isbn.padRight(20)} ${isValidIsbn(isbn) ? 'valid' : 'invalid'}');
}
}7
978-1-23456-789-7 valid
978-1-23456-789-2 invalid
978 9966 25 431 3 valid
97899662543X3 invalid
12345 invalidThe two functions divide the work along the line this lesson drew. isbnCheckDigit has a precondition (exactly twelve digits) and throws a FormatException when it is broken, documented with /// and [FormatException] so that editors show it to callers. isValidIsbn is meant for untrusted input, so it never throws: it cleans the text with a regular expression (a raw string, r'[-\s]', so the backslash reaches RegExp intact), rejects the wrong length early, and catches the one exception it expects, with on FormatException, turning it into false. The X in the fourth candidate makes int.tryParse fail inside isbnCheckDigit, and the catch handles it.
i.isEven uses a getter on int, padRight(20) lines up the output, and the ternary isValidIsbn(isbn) ? 'valid' : 'invalid' sits inside the interpolation. The arithmetic (10 - sum % 10) % 10 handles the case where the sum is already a multiple of 10, when the check digit must be 0, not 10.
Functions the way Dart teams write them
A few habits, most of them from Effective Dart, make Dart code read the way other Dart programmers expect:
- Top-level functions are fine. Unlike Java, Dart does not need a class to hold a function. A class with only static methods is a smell; write top-level functions in a library instead.
- Avoid positional
boolparameters.send(message, true)hides its meaning;send(message, urgent: true)does not. The same goes for most parameters whose meaning is not obvious from the function name. - Use
=>for one-expression bodies and braces otherwise. Do not squeeze statements into an arrow. - Document public functions with
///comments, starting with a one-sentence summary in the third person ("Returns ...", "Throws ..."), and refer to parameters and types in square brackets so tools can link them. - Let the formatter decide layout.
dart formatbreaks long parameter lists one per line when a trailing comma or the line length calls for it; nobody argues about where line breaks go.
Common misconceptions
Misconception
"Named parameters are optional, so I can leave any of them out." Only if they have a default or a nullable type. A parameter marked required must be passed, and the compiler enforces it, which is why null-safe APIs use required for every named argument that has no sensible default.
Misconception
"catch (e) is the safe way to make sure nothing crashes." A catch-all also swallows Errors, which are bugs, and turns them into silent misbehaviour. Catch the specific exceptions you can handle, with on, and let the rest reach a top-level handler that logs them.
Misconception
"A closure remembers the value a variable had when the closure was created." It remembers the variable. If the variable changes later, the closure sees the new value, as the shared example showed. Only for loop variables are fresh in each iteration; to freeze a value, copy it into a final local inside the loop body.
Misconception
"assert will stop bad input in production." Assertions are off in dart run by default and stripped from Flutter release builds. Validate input with ordinary code and exceptions.
Exercises
1. Control flow, functions and exceptions
Warm-upComputationalWhat does this program print?
String size(int n) => switch (n) {
0 => 'none',
1 || 2 || 3 => 'few',
_ => 'many',
};
void main() => print([0, 2, 7].map(size).join(' '));
2. Control flow, functions and exceptions
CoreComputationalGiven void book({required String room, int nights = 1, String? note}), which calls compile? Choose every one that does.
3. Control flow, functions and exceptions
CoreComputationalWhat does the first line of output of this program look like?
void main() {
var x = 1;
final f = () => x * 10;
x = 4;
final fs = <int Function()>[];
for (var i = 0; i < 3; i++) {
fs.add(() => i);
}
print('${f()} ${fs.map((g) => g()).join()}');
}
4. Control flow, functions and exceptions
StretchComputationalWhat does this program print?
void main() {
var count = 0;
outer:
for (var i = 1; i <= 3; i++) {
for (var j = 1; j <= 3; j++) {
if (j == i) continue outer;
count += 10 * i + j;
}
}
print(count);
}
5. Control flow, functions and exceptions
CoreComputationalWhat does this program print?
int risky(int n) {
if (n.isOdd) throw FormatException('odd');
return n ~/ 2;
}
void main() {
final out = <String>[];
for (final n in [4, 3]) {
try {
out.add('${risky(n)}');
} on FormatException {
out.add('E');
} finally {
out.add('F');
}
}
print(out.join());
}
6. Control flow, functions and exceptions
CoreHumanYou are writing Temperature.parse(String text). Users type the text into a form. How should the function report text that is not a number?
7. Control flow, functions and exceptions
Warm-upHumanA program contains assert(total >= 0, 'total went negative'); and is run with dart run main.dart. total is −5 when the line runs. What happens?
Further reading and resources
- Branches
- Loops
- Functions
- Error handling
- Effective Dart: UsageIncludes the guidance on exceptions, errors and catch clauses.