Functions and Records
Closures
Capturing Outer State
A function declared inside another function can read and update names from the enclosing scope. The captured binding lives as long as the inner function does, so a factory can hand out a function that owns private mutable state.
Program
Play the program to build a counter closure and call it twice.
closures.dart
int Function() makeCounter() {
var count = 0;
return () {
count += 1;
return count;
};
}
void main() {
var next = makeCounter();
var a = next();
var b = next();
print('$a $b');
}
closure
An inner function captures names from its enclosing scope.
captured mutation
`count += 1` updates the same binding across calls; the closure carries the state.
factory function
`int Function() makeCounter()` returns a fresh zero-argument function with its own private `count`.