Dart Closures
Dart Closures
A function can use variables that are defined outside of it.
A closure is a function that remembers these outside variables, even when it is called later, in another place.
In this example, the anonymous function uses the variable greeting from main():
Example
void main() {
var greeting = 'Hello';
var greet = (String name) => '$greeting, $name!';
print(greet('Liam'));
}
Try it Yourself »
Result:
Hello, Liam!
The function greet is a closure, because it uses greeting, which is not one of its parameters.
A Counter Example
Closures become really useful when a function returns another function.
The function makeCounter() creates a variable count and returns a function that adds 1 to it:
Example
int Function() makeCounter() {
var count = 0;
return () {
count++;
return count;
};
}
void main() {
var counter = makeCounter();
print(counter());
print(counter());
print(counter());
}
Try it Yourself »
Result:
1
2
3
Example Explained
- The return type
int Function()means thatmakeCounter()returns a function that takes no parameters and returns anint. - When
makeCounter()is finished, its local variablecountwould normally be gone. - But the returned function still uses
count, so Dart keeps it alive. - Each call to
counter()changes the samecount, so the result goes up by 1 every time.
Each Closure Has Its Own Variables
Every call to makeCounter() creates a new count variable.
So two counters do not share their values:
Example
int Function() makeCounter() {
var count = 0;
return () {
count++;
return count;
};
}
void main() {
var applesCounter = makeCounter();
var orangesCounter = makeCounter();
print(applesCounter());
print(applesCounter());
print(orangesCounter());
}
Try it Yourself »
Result:
1
2
1
Closures With Parameters
A closure can also remember a parameter of the outer function.
Here, makeMultiplier() returns a function that multiplies a number by factor:
Example
int Function(int) makeMultiplier(int factor) {
return (int x) => x * factor;
}
void main() {
var timesTwo = makeMultiplier(2);
var timesThree = makeMultiplier(3);
print(timesTwo(5));
print(timesThree(5));
}
Try it Yourself »
Result:
10
15
The function in timesTwo remembers that factor is 2, and the function in timesThree remembers that factor is 3.
Closures See the Current Value
A closure does not copy the value of a variable.
It uses the variable itself, so it always sees the current value:
Example
void main() {
var name = 'Emma';
var greet = () => print('Hello, $name');
greet();
name = 'Noah';
greet();
}
Try it Yourself »
Result:
Hello, Emma
Hello, Noah
Remember: A closure is just a function that uses variables from the place where it was created.
You use closures every time you pass an anonymous function to methods like forEach() or where() and use a variable from outside it.