What is a closure in Dart and what is it used for?
Show answer — try answering out loud first
A closure is a function that "remembers" the variables from the scope where it was created, even after that scope has finished. It's used to keep private state and to create configurable functions (function factories).
In Dart, functions are first-class citizens: you can store them in variables, pass them as arguments, and return them from another function. When you define a function inside another one, the inner function keeps access to the variables of the outer one. Even after the outer function has finished, the inner one still "remembers" those variables. That combination of function + remembered variables is a closure.
It's used to:
- Keep private state (variables that only that function can touch).
- Create functions from other functions (function factories).
- Callbacks,
onPressed, and pretty much any lambda that captures variables from its surroundings in Flutter.
// Counter with private state thanks to the closure
Function createCounter() {
int count = 0; // gets "enclosed" in the closure
return () {
count++;
return count;
};
}
// Factory: each function remembers its own "factor"
int Function(int) multiplyBy(int factor) {
return (int number) => number * factor;
}
void main() {
final counter = createCounter();
print(counter()); // 1
print(counter()); // 2
print(counter()); // 3
// "count" is not accessible from the outside: it's private
final doubler = multiplyBy(2);
final triple = multiplyBy(3);
print(doubler(5)); // 10
print(triple(5)); // 15
}
Assuming every call shares the same state. It doesn't: each time you call createCounter() you get a brand-new closure with its own count. Two counters created separately don't share a value. Getting this wrong leads to bugs where you think a counter "reset itself" when in reality you created another one.
"A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished. In Dart I use them a lot because functions are first-class: I can return a function that keeps a private variable, like a counter, or create a factory like
multiplyBy(2). In Flutter, everyonPressedcallback that uses a variable from its widget is effectively a closure."
Create a function createGreeting(String greeting) that returns another function which takes a name and returns the full greeting. Example: createGreeting("Hello")("Mike") should return "Hello, Mike".
See solution
String Function(String) createGreeting(String greeting) {
return (String name) => "$greeting, $name";
}
void main() {
print(createGreeting("Hello")("Mike")); // "Hello, Mike"
}