On this page11 sections
Lecture 048: Anonymous Functions
| Day | Extra Topics |
| Lecture | 048 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
Most functions have a name, like
mainoradd. An anonymous function has no name. You write it right where it's needed, usually to hand it to another function likeforEach,maporwhere. You'll see them everywhere in Flutter.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 025–027 (functions) and 039–040 (lambdas, higher-order functions). Lists and maps from lectures 011–014.
Learning Objectives
- Write an anonymous function, in block and arrow form
- Store one in a variable and call it
- Pass one to
forEach,map,where,sortandfold - Run a function immediately after writing it
1. A Function Without a Name
A normal function:
int square(int n) {
return n * n;
}The same idea without a name, stored in a variable:
var cube = (int n) {
return n * n * n;
};
print(cube(3)); // 27The shape is (parameters) { body }. Notice the ; after the closing }: the whole thing is
one statement, var cube = ...;.
2. Arrow Form
When the body is a single expression, use =>:
var twice = (int n) => n * 2;
print(twice(5)); // 10(int n) => n * 2 means exactly the same as (int n) { return n * 2; }.
3. Passing Functions to Other Functions
This is where anonymous functions shine. Lists have methods that take a function and call it for each item:
var fruits = ['apple', 'banana', 'mango'];
fruits.forEach((fruit) {
print('I like $fruit');
});
var lengths = fruits.map((f) => f.length).toList();
print(lengths); // [5, 6, 5]
var longOnes = fruits.where((f) => f.length > 5).toList();
print(longOnes); // [banana]
var numbers = [5, 2, 9, 1];
numbers.sort((a, b) => b.compareTo(a)); // largest first
print(numbers); // [9, 5, 2, 1]| Method | The function you pass… | Result |
|---|---|---|
forEach(f) | runs for each item | nothing returned |
map(f) | turns each item into a new value | new values (add .toList()) |
where(f) | returns true to keep an item | the kept items (add .toList()) |
sort(f) | compares two items | sorts the list in place |
fold(start, f) | combines a running total with each item | one final value |
The parameter type is usually left out ((fruit) { ... }): Dart already knows fruits holds
strings.
4. Calling a Function Immediately
Wrap it in parentheses and add ():
(() {
print('Runs right away');
})();You won't need this often, but you'll recognise it when you see it.
Code Examples
Example 1: A Shopping Cart
void main() {
var cart = [
{'item': 'Pen', 'price': 40, 'qty': 3},
{'item': 'Notebook', 'price': 150, 'qty': 2},
{'item': 'Bag', 'price': 1800, 'qty': 1},
];
print('--- Items ---');
cart.forEach((line) {
print('${line['item']} × ${line['qty']}');
});
var lineTotals = cart.map((line) => (line['price'] as int) * (line['qty'] as int)).toList();
print('Line totals: $lineTotals');
var total = lineTotals.fold(0, (sum, value) => sum + value);
print('Total: Rs $total');
var expensive = cart.where((line) => (line['price'] as int) > 100).map((line) => line['item']).toList();
print('Over Rs 100: $expensive');
}Output
--- Items ---
Pen × 3
Notebook × 2
Bag × 1
Line totals: [120, 300, 1800]
Total: Rs 2220
Over Rs 100: [Notebook, Bag]as int tells Dart the map value is a number. The last line chains where and map: first
keep the expensive lines, then take just their names.
Common Beginner Mistakes
1. Forgetting () to call it
var greet = () => print('Hi');
greet; // does nothing: no error, no output
greet(); // Hi2. Wrong number of arguments
var add = (int a, int b) => a + b;
print(add(2));Error: Too few positional arguments: 2 required, 1 given.3. Forgetting .toList(): map and where give back a lazy iterable. Printing it shows
(5, 6, 5) with round brackets. Add .toList() when you need a real list.
4. Mixing => with a block
var f = (int n) => { return n * 2; };Error: Unexpected token 'return'.After =>, Dart expects a single expression, and { ... } there means a set literal. Use
either (n) => n * 2 or (n) { return n * 2; }.
5. fold straight inside print
print([1, 2, 3, 4].fold(0, (sum, n) => sum + n));Error: The operator '+' isn't defined for the type 'Object?'.Here Dart can't tell what type the running total is. Store it in a variable first
(var total = [...].fold(0, ...);), or say the type: fold<int>(0, (sum, n) => sum + n).
Practice Questions
- Rewrite
(int n) { return n + 1; }in arrow form. - What does
[1, 2, 3].map((n) => n * 10).toList()give? - What does
[4, 7, 10, 13].where((n) => n > 8).toList()give? - Write code that prints every name in
['Ali', 'Sara']usingforEach. - After
var total = [1, 2, 3, 4].fold(0, (sum, n) => sum + n);, what istotal?
Practice Answers
(int n) => n + 1[10, 20, 30][10, 13]['Ali', 'Sara'].forEach((name) => print(name));10
Key Takeaways
- An anonymous function is
(params) { body }or(params) => expression, with no name. - Store it in a variable, or pass it straight into another function.
forEach,map,where,sortandfoldall take a function.- Add
()to call it and.toList()aftermap/where.