Dart Function Values
A function value is a function treated as a stored value. A list can run a stored function on each of its items with forEach.
print passed as a value
print itself passes into forEach in this program. Each number appears on its own line.
void main() {
var numbers = [1, 2, 3];
numbers.forEach(print);
}A named function passed by name
showDoubled passes into forEach by its name alone. Each printed value is double its list item.
void showDoubled(int n) {
print(n * 2);
}
void main() {
var numbers = [1, 2, 3];
numbers.forEach(showDoubled);
}An anonymous function in forEach
The function inside forEach has no name in this program. Each printed value is ten more than its list item.
void main() {
var numbers = [1, 2, 3];
numbers.forEach((x) => print(x + 10));
}A variable holding a function
addOne holds an anonymous function in this program. The two calls add one to each input.
void main() {
var addOne = (int n) => n + 1;
print(addOne(4));
print(addOne(9));
}Example
void showDoubled(int n) {
print(n * 2);
}
void main() {
var numbers = [2, 4];
numbers.forEach(showDoubled);
numbers.forEach((x) => print(x + 100));
var label = (int n) => 'Number $n';
print(label(7));
}Key points
- A function name without parentheses stands for the function itself.
- Parentheses after a name call the function.
- An anonymous function is a function with no name.
- A variable can hold an anonymous function.
- Use forEach to run one function on every item in a list.
In this example, showDoubled passes to forEach by name and prints 4 and 8. An anonymous function then adds 100 to each item and prints 102 and 104. The variable label holds an anonymous function that builds text. The last print shows the text for the input 7.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does a function name without parentheses stand for?