On this page12 sections
Lecture 041: Lexical Closures
| Day | 14: Lambdas, Higher-Order Functions & Closures |
| Lecture | 041 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
In Lecture 040,
multiplier(2)returned a function that still knewfactorwas2, even aftermultiplierhad finished. How? The returned function closes over the variables around it, and keeps them alive. That's a closure, and it's how Flutter callbacks remember their data.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 039 (lambdas) and 040 (higher-order functions).
Learning Objectives
- Explain lexical scope: a function can use the variables around where it was written
- Explain what a closure is
- Build a counter that remembers its count
- Know that each closure gets its own copy of the captured variables
- Use closures to build customised functions
1. Lexical Scope
"Lexical" means "decided by where the code is written". A function can use any variable that's visible where the function is written:
var total = 0;
var addToTotal = (int n) => total += n;
addToTotal(5);
addToTotal(10);
print(total); // 15The lambda uses total, a variable from outside it, and can even change it.
2. Closures: Remembering After the Function Ends
Normally a function's local variables disappear when it finishes. But if it returns a lambda that uses them, they stay alive for that lambda:
int Function() counter() {
var count = 0;
return () => ++count;
}
var c1 = counter();
print(c1()); // 1
print(c1()); // 2
print(c1()); // 3counter() has finished, yet c1 still reads and updates count. The lambda plus the variables
it captured is called a closure.
3. Each Closure Has Its Own Variables
Every call to counter() creates a new count:
var c2 = counter();
print(c2()); // 1: its own count
print(c1()); // 4: c1 carries on from 3That's how multiplier(2) and multiplier(10) in Lecture 040 each kept their own factor.
4. Closures That Customise
String Function(String) greeter(String greeting) {
return (name) => '$greeting, $name!';
}
var hello = greeter('Hello');
var salam = greeter('Assalam-o-Alaikum');
print(hello('Ali')); // Hello, Ali!
print(salam('Sara')); // Assalam-o-Alaikum, Sara!5. Closures in Loops
In a for loop, each round gets a fresh loop variable, so each closure remembers its own value:
var callbacks = <void Function()>[];
for (var i = 1; i <= 3; i++) {
callbacks.add(() => print('callback $i'));
}
for (var cb in callbacks) {
cb();
}Output
callback 1
callback 2
callback 3Code Examples
Example 1: Loggers and a Wallet
void Function(String) makeLogger(String tag) {
var lineNumber = 0;
return (message) {
lineNumber++;
print('[$tag #$lineNumber] $message');
};
}
double Function(double) makeAccount(double start) {
var balance = start;
return (change) {
balance += change;
return balance;
};
}
void main() {
var authLog = makeLogger('AUTH');
var cartLog = makeLogger('CART');
authLog('User signed in');
cartLog('Added shoes');
authLog('Password changed');
cartLog('Checkout started');
var wallet = makeAccount(1000);
print(wallet(500));
print(wallet(-200));
}Output
[AUTH #1] User signed in
[CART #1] Added shoes
[AUTH #2] Password changed
[CART #2] Checkout started
1500.0
1300.0Each logger keeps its own tag and lineNumber. The wallet's balance can only be changed by
calling wallet(...): no other code can reach it. A closure can hide data much like a private
field.
Common Beginner Mistakes
1. Creating a new closure every time
print(counter()());
print(counter()());
print(counter()());Output
1
1
1Each counter() call makes a brand-new counter starting at 0. Store it once
(var c = counter();) and call c() repeatedly.
2. Using a variable that isn't in scope
int Function() makeCounter() {
return () => ++count;
}Error: Getter not found: 'count'.A closure can only capture variables that exist where it's written. Declare var count = 0;
inside makeCounter, before the return.
3. Expecting shared state between closures: c1 and c2 from counter() never share a
count. If you want shared state, both closures must come from the same call.
Practice Questions
- What is a closure, in one sentence?
var a = counter(); a(); a();What does the nexta()return?var b = counter();after the above. What doesb()return?- Write
adder(int x)that returns a function addingxto its argument. - Why does
print(counter()())always print1?
Practice Answers
- A function together with the variables it captured from where it was written, which stay alive as long as the function does.
31.bhas its own count.int Function(int) adder(int x) => (n) => n + x;- Each
counter()creates a new closure with a freshcount = 0.
Key Takeaways
- Lexical scope: a function can use the variables visible where it's written.
- A closure keeps those variables alive after the outer function has finished.
- Each call to the outer function creates new captured variables.
- Closures build customised functions (
greeter('Hello')) and can keep data private. - Store a closure once if it should remember state between calls.