On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Lexical Scope
  4. 2. Closures: Remembering After the Function Ends
  5. 3. Each Closure Has Its Own Variables
  6. 4. Closures That Customise
  7. 5. Closures in Loops
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 041: Lexical Closures

Day14: Lambdas, Higher-Order Functions & Closures
Lecture041 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

In Lecture 040, multiplier(2) returned a function that still knew factor was 2, even after multiplier had 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:

dart
var total = 0;
var addToTotal = (int n) => total += n;
addToTotal(5);
addToTotal(10);
print(total);   // 15

The 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:

dart
int Function() counter() {
  var count = 0;
  return () => ++count;
}

var c1 = counter();
print(c1());   // 1
print(c1());   // 2
print(c1());   // 3

counter() 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:

dart
var c2 = counter();
print(c2());   // 1: its own count
print(c1());   // 4: c1 carries on from 3

That's how multiplier(2) and multiplier(10) in Lecture 040 each kept their own factor.

4. Closures That Customise

dart
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:

dart
var callbacks = <void Function()>[];
for (var i = 1; i <= 3; i++) {
  callbacks.add(() => print('callback $i'));
}
for (var cb in callbacks) {
  cb();
}

Output

code
callback 1
callback 2
callback 3

Code Examples

Example 1: Loggers and a Wallet

dart
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

code
[AUTH #1] User signed in
[CART #1] Added shoes
[AUTH #2] Password changed
[CART #2] Checkout started
1500.0
1300.0

Each 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

dart
print(counter()());
print(counter()());
print(counter()());

Output

code
1
1
1

Each 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

dart
int Function() makeCounter() {
  return () => ++count;
}
code
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

  1. What is a closure, in one sentence?
  2. var a = counter(); a(); a(); What does the next a() return?
  3. var b = counter(); after the above. What does b() return?
  4. Write adder(int x) that returns a function adding x to its argument.
  5. Why does print(counter()()) always print 1?

Practice Answers

  1. A function together with the variables it captured from where it was written, which stay alive as long as the function does.
  2. 3
  3. 1. b has its own count.
  4. int Function(int) adder(int x) => (n) => n + x;
  5. Each counter() creates a new closure with a fresh count = 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.