Python Lexical Scope & Stateful Closures
Dart is lexically scoped: the structure of curly braces `{ }` determines variable visibility. A **Closure** is a function object that retains access to variables from its lexical enclosing scope even after that outer scope has finished execution. Closures enable powerful state encapsulation and factory generators without writing full class boilerplate.
"A closure is like a backpack you pack at home before going on a hike: even when you are far away on the mountain trail (outside the home scope), you can still reach into your backpack to use the water bottle you packed."
Deep Dive: How It Works
Lexical Scope Chain: Inner functions can read and mutate variables declared in outer enclosing blocks.
Variable Capture: Dart captures the variable reference itself, preserving state across successive invocations.
Function Factories: Generating specialized functions (e.g. `makeMultiplier(3)`) dynamically.
Syntax Blueprint
Function makeCounter() {
int count = 0;
return () => ++count; // Captures and increments count
}Factory function returning a stateful closure that encapsulates private state.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Assuming closures capture a copy of a variable value at declaration time.Why it happens: Closures capture the mutable variable reference; mutating the variable reflects across all closures sharing that scope.
How to fix: Create a local `final` binding inside the block if you need snapshot isolation.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Create Multiplier Closure Factory
Define `int Function(int) makeMultiplier(int factor) => (int n) => n * factor;`.
In `main()`, create `final triple = makeMultiplier(3);`.
Print `Triple 7: ${triple(7)}`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.