Closures & Lexical Scope
Dart is lexically scoped: where a variable is visible is determined by where it appears in the source code — by the curly braces around it. A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished running.
Lexical scope
Each pair of braces opens a new scope. Inner scopes can see outer variables; outer scopes can't see inner ones.
var level = 'top-level';
void main() {
var level1 = 'main';
void inner() {
var level2 = 'inner';
print('$level / $level1 / $level2');
}
inner();
if (true) {
var blockOnly = 'block';
print(blockOnly);
}
// print(blockOnly); // compile error: not defined here
}top-level / main / inner
block
Shadowing
An inner declaration with the same name hides the outer one within its scope:
var name = 'global';
void main() {
print(name);
var name2 = name;
{
var name = 'shadow';
print(name);
}
print(name2);
}global
shadow
global
Shadowing is legal but often confusing — linters can warn about it.
Closures capture variables, not values
A closure keeps a live reference to the captured variable. If the variable changes later, the closure sees the new value:
void main() {
var greeting = 'Hello';
String greet(String who) => '$greeting, $who';
print(greet('Kim'));
greeting = 'Goodbye';
print(greet('Kim'));
}Hello, Kim
Goodbye, Kim
Functions that create functions
The classic closure example: a counter factory. Each call to makeCounter creates a fresh count variable, and the returned function keeps it alive.
int Function() makeCounter({int start = 0, int step = 1}) {
var count = start;
return () {
count += step;
return count;
};
}
void main() {
final a = makeCounter();
final b = makeCounter(start: 100, step: 10);
print(a());
print(a());
print(b());
print(a());
print(b());
}1
2
110
3
120
a and b each have their own private count. Nothing outside can touch it — closures are a lightweight way to encapsulate state.
Practical uses
Configuring callbacks
bool Function(int) between(int low, int high) => (n) => n >= low && n <= high;
void main() {
final temps = [12, 25, 31, 18, 38, 22];
final pleasant = between(18, 26);
final hot = between(30, 50);
print(temps.where(pleasant).toList());
print(temps.where(hot).toList());
}[25, 18, 22]
[31, 38]
Memoisation
A closure can hold a cache that survives between calls:
int Function(int) memoize(int Function(int) f) {
final cache = <int, int>{};
return (n) => cache.putIfAbsent(n, () {
print(' computing $n');
return f(n);
});
}
void main() {
final slowSquare = memoize((n) => n * n);
print(slowSquare(4));
print(slowSquare(4));
print(slowSquare(5));
} computing 4
16
16
computing 5
25
Loop variables and closures
In a for loop, Dart creates a new variable per iteration, so each closure captures its own value:
final printers = [for (var i = 0; i < 3; i++) () => print(i)];
for (final p in printers) p(); // prints 0, 1, 2 — not 3, 3, 3But a variable declared outside the loop is shared by every closure:
var i = 0;
final printers = <void Function()>[];
while (i < 3) {
printers.add(() => print(i));
i++;
}
for (final p in printers) p(); // prints 3, 3, 3| Situation | What a closure sees |
|---|---|
Variable declared in the for (var i …) header |
That iteration's value |
| Variable declared outside the loop | The latest value at call time |
final variable |
Always the same value (it can't change) |
Tip: When you want a closure to "freeze" a value, copy it into a
finallocal first:final snapshot = value; callbacks.add(() => use(snapshot));.
Test yourself
A closure captures x, then x is changed before the closure runs. What does the closure see?
- The old value
- The new value
- null
- A compile error occurs
Two counters are created by calling makeCounter() twice. Do they share the same count?
- Yes, always
- No — each call creates a new captured variable
- Only if count is static
- Only if count is final
What determines where a variable is visible in Dart?
- The order functions are called
- Its position in the source code (lexical scope)
- Whether it is final
- The import order