Anonymous Functions and Closures
Prerequisites: Named and optional parameters
In Dart, functions are values: you can store them in variables, pass them to other functions, and return them. An anonymous function is a function without a name, written inline.
Real-world analogy: an anonymous function is an instruction slip you hand to someone along with a job — "for each parcel, check the weight like this". They decide when to follow it.
Syntax
void main() {
final double = (int n) => n * 2;
final add = (int a, int b) {
return a + b;
};
print(double(21));
print(add(2, 3));
}
42
5
Passing functions to functions
A function that takes or returns another function is a higher-order function. The parameter's type describes the function it expects:
void repeatTask(int times, void Function(int pass) task) {
for (var i = 1; i <= times; i++) {
task(i);
}
}
void main() {
repeatTask(3, (pass) {
print('Pass $pass');
});
final names = ['Linus', 'ada', 'Grace'];
names.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(names);
}
Pass 1
Pass 2
Pass 3
[ada, Grace, Linus]
void Function(int pass) is a function type: "takes an int,
returns nothing". Flutter uses this everywhere — onPressed: () { ... }
passes a function to a button.
Tear-offs
You can pass an existing function by name, without calling it — a tear-off:
bool isLong(String word) => word.length > 4;
void main() {
final words = ['fig', 'banana', 'kiwi', 'cherry'];
print(words.where(isLong).toList());
}
[banana, cherry]
Closures
A function remembers the variables around it when it was created — it's a closure:
int Function() makeCounter() {
var count = 0;
return () => ++count;
}
void main() {
final next = makeCounter();
next();
next();
print(next());
}
3
count would normally disappear when makeCounter returns, but the
closure keeps it alive.
Practice
Sort ['banana', 'fig', 'apple'] by word length, shortest first.
Show solution
void main() {
final words = ['banana', 'fig', 'apple'];
words.sort((a, b) => a.length.compareTo(b.length));
print(words);
}
[fig, apple, banana]