On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. A Function Without a Name
  4. 2. Arrow Form
  5. 3. Passing Functions to Other Functions
  6. 4. Calling a Function Immediately
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 048: Anonymous Functions

DayExtra Topics
Lecture048 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

Most functions have a name, like main or add. An anonymous function has no name. You write it right where it's needed, usually to hand it to another function like forEach, map or where. 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, sort and fold
  • Run a function immediately after writing it

1. A Function Without a Name

A normal function:

dart
int square(int n) {
  return n * n;
}

The same idea without a name, stored in a variable:

dart
var cube = (int n) {
  return n * n * n;
};
print(cube(3));   // 27

The 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 =>:

dart
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:

dart
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]
MethodThe function you pass…Result
forEach(f)runs for each itemnothing returned
map(f)turns each item into a new valuenew values (add .toList())
where(f)returns true to keep an itemthe kept items (add .toList())
sort(f)compares two itemssorts the list in place
fold(start, f)combines a running total with each itemone 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 ():

dart
(() {
  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

dart
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

code
--- 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

dart
var greet = () => print('Hi');
greet;          // does nothing: no error, no output
greet();        // Hi

2. Wrong number of arguments

dart
var add = (int a, int b) => a + b;
print(add(2));
code
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

dart
var f = (int n) => { return n * 2; };
code
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

dart
print([1, 2, 3, 4].fold(0, (sum, n) => sum + n));
code
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

  1. Rewrite (int n) { return n + 1; } in arrow form.
  2. What does [1, 2, 3].map((n) => n * 10).toList() give?
  3. What does [4, 7, 10, 13].where((n) => n > 8).toList() give?
  4. Write code that prints every name in ['Ali', 'Sara'] using forEach.
  5. After var total = [1, 2, 3, 4].fold(0, (sum, n) => sum + n);, what is total?

Practice Answers

  1. (int n) => n + 1
  2. [10, 20, 30]
  3. [10, 13]
  4. ['Ali', 'Sara'].forEach((name) => print(name));
  5. 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, sort and fold all take a function.
  • Add () to call it and .toList() after map/where.