Not all functions need a name. Sometimes you just need a quick, disposable function to perform a small task, like sorting a list or handling a button click.
1. Anonymous Functions (Lambdas)
Functions do not always need names. You can define a function directly where you need it, often as a parameter to another function.
Inline Functions
1var list = ['Apples', 'Bananas', 'Oranges'];2 3// The function (item) { print(item); } is anonymous4list.forEach((item) {5 print('${item.toUpperCase()}');6});HintThis is extremely common in Flutter for callbacks, like onPressed: () { ... }.
2. The Arrow Syntax (=>)
A shorthand for functions that contain ONLY ONE expression. It automatically returns the result of that expression.
Concise Logic
1// Long way2int add(int a, int b) {3 return a + b;4}5 6// Arrow way (Fat Arrow)7int addShort(int a, int b) => a + b;8 9// With Lists (Expression body)10var nums = [1, 2, 3];11var doubled = nums.map((n) => n * 2).toList(); 12print(doubled); // [2, 4, 6]Hint=> expr is equivalent to { return expr; }. You cannot put an if statement or multiple lines inside an arrow function.
3. Functions as Objects (First-Class Citizens)
You can assign functions to variables, pass them as arguments, or return them from other functions.
Passing Logic Around
1// A function that expects another function as input2void repeatedly(int times, void Function(int) task) {3 for (int i = 0; i < times; i++) {4 task(i);5 }6}7 8void main() {9 // We pass an anonymous arrow function10 repeatedly(3, (index) => print('Attempt #${index + 1}'));11}HintThis pattern is how buttons work: you give the button a function, and the button calls it when clicked.
4. Closures
A closure is a function object that has access to variables in its lexical scope, even when the function is used outside of its original scope.
Capturing State
1Function makeAdder(int amountToAdd) {2 // This function "remembers" amountToAdd3 return (int i) => i + amountToAdd;4}5 6void main() {7 var addFive = makeAdder(5);8 var addTen = makeAdder(10);9 10 print(addFive(2)); // 711 print(addTen(2)); // 1212}HintThe inner function "closed over" the variable amountToAdd.
Loot collected
Key takeaways- Anonymous functions have no name and are used for quick tasks.
- Use Arrow syntax (
=> expression) for one-line functions to keep code clean. - The
=>arrow automatically returns the value; do not usereturnor{}with it. - Functions can be passed as arguments just like numbers or strings.
Side quests
Practice exercises
Exercise 1: Convert to Arrow
Rewrite this using arrow syntax: int double(int x) { return x * 2; }
Reveal solutionHide solution
1int double(int x) => x * 2;Exercise 2: forEach Arrow
Use an arrow function inside forEach to print every item in [1, 2, 3].
Reveal solutionHide solution
1list.forEach((n) => print(n));