Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 61 ยท Functions

First-Class Functions, Closures and Typedefs

Learn how Dart treats functions as values: function types, anonymous functions, closures that capture variables, typedef aliases and tear-offs.

In Dart, a function is an object. You can store it in a variable, pass it to another function, return it from a function, or keep it in a list. Languages that allow this call functions first-class. It is the idea behind list.map(...), event callbacks in Flutter, and many everyday patterns.

This lesson covers function types, anonymous functions, closures (functions that remember the variables around them), typedef aliases and tear-offs. It builds on Functions and Parameters. The Dart code is read-only; the TypeScript stand-ins are runnable and behave the same way.

Functions as values

Because a function is a value, a variable can hold one:

DART
int add(int a, int b) => a + b;
int multiply(int a, int b) => a * b;

void main() {
  int Function(int, int) operation = add;
  print(operation(3, 4)); // 7

  operation = multiply;
  print(operation(3, 4)); // 12
}

The type int Function(int, int) reads as "a function that takes two ints and returns an int". Write the return type first, then the word Function, then the parameter types in parentheses. Parameters may have names there too: int Function(int a, int b).

Functions can also be passed to other functions. A function that takes a function is called a higher-order function:

DART
List<int> transform(List<int> items, int Function(int) change) {
  final result = <int>[];
  for (final item in items) {
    result.add(change(item));
  }
  return result;
}

void main() {
  print(transform([1, 2, 3], (n) => n * 10)); // [10, 20, 30]
}

The call passes (n) => n * 10, an anonymous function (also called a lambda). It has no name, just parameters and a body. With an arrow, the body is one expression; with braces, it can contain statements:

DART
final describe = (int n) {
  if (n.isEven) return 'even';
  return 'odd';
};

Dart infers the parameter types of an anonymous function from the context, which is why (n) => n * 10 needs no int above.

TypeScript Storing and passing functions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Returning functions

A function can build and return another function. This is how you create specialized helpers from a general recipe:

DART
int Function(int) adder(int amount) {
  return (int value) => value + amount;
}

void main() {
  final addFive = adder(5);
  final addTen = adder(10);
  print(addFive(1));  // 6
  print(addTen(1));   // 11
}

The returned function uses amount, a parameter of adder, even though adder has already finished. That works because of closures.

Closures

A closure is a function together with the variables it uses from the scope where it was created. The function keeps access to those variables for as long as it exists, even after the original scope has ended.

DART
int Function() makeCounter() {
  var count = 0;
  return () {
    count++;
    return count;
  };
}

void main() {
  final a = makeCounter();
  final b = makeCounter();
  print(a()); // 1
  print(a()); // 2
  print(a()); // 3
  print(b()); // 1
}

Each call to makeCounter creates a fresh count. The function it returns captures that variable, not a copy of its value, so changes persist between calls. Counters a and b are independent because they captured different variables.

flowchart LR
    M1["makeCounter() call 1"] --> C1["count = 0"]
    M2["makeCounter() call 2"] --> C2["count = 0"]
    C1 --- A["closure a"]
    C2 --- B["closure b"]

Each call creates its own variable, and each closure keeps its own variable alive.

This is how lexical scope (from the functions lesson) extends to function values: names are resolved where the function is written, not where it is called.

Closures are useful whenever you need small private state, or when you want to configure a callback:

DART
void main() {
  final tags = <String>[];
  void log(String message) => tags.add('[app] $message');

  log('start');
  log('done');
  print(tags); // [[app] start, [app] done]
}
TypeScript Closures remember their variables (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

typedef: naming a function type

Long function types get hard to read, especially in parameter lists. A typedef gives a type a name:

DART
typedef BinaryOperation = int Function(int, int);
typedef Predicate<T> = bool Function(T value);

int apply(BinaryOperation op, int a, int b) => op(a, b);

List<T> keepIf<T>(List<T> items, Predicate<T> test) {
  return [for (final item in items) if (test(item)) item];
}

void main() {
  print(apply((a, b) => a - b, 9, 4));               // 5
  print(keepIf([1, 2, 3, 4, 5, 6], (n) => n.isEven)); // [2, 4, 6]
}

A typedef is just an alias: it does not create a new type, and any function with a compatible shape can be used. Typedefs can be generic, as Predicate<T> shows. Generics are explained in Generics. Dart's newer typedef Name = Type; form works for any type, not only functions, for example typedef Json = Map<String, Object?>;.

Flutter uses this a lot: VoidCallback is a typedef for void Function(), and ValueChanged<T> is one for void Function(T).

TypeScript Naming function types (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Tear-offs

When an existing function already has the right shape, you do not need to wrap it in an anonymous function. Using the function's name without calling it gives you the function as a value. This is a tear-off.

DART
void main() {
  final names = ['Ada', 'Grace', 'Linus'];

  names.forEach(print);               // instead of (n) => print(n)

  final numbers = ['1', '2', '3'].map(int.parse).toList();
  print(numbers);                     // [1, 2, 3]

  final lengths = names.map((s) => s.length);
  print(lengths.toList());            // [3, 5, 5]
}

print and int.parse are torn off: no parentheses, no arguments. The analyzer even has a lint, unnecessary_lambdas, that suggests a tear-off when your lambda only forwards its arguments.

Tear-offs work for methods and constructors too:

DART
class Point {
  final int x;
  final int y;
  Point(this.x, this.y);
}

void main() {
  final shout = 'hello'.toUpperCase; // method tear-off, bound to 'hello'
  print(shout());                    // HELLO

  final make = Point.new;            // constructor tear-off
  final p = make(1, 2);
  print('${p.x}, ${p.y}');           // 1, 2
}

A method tear-off stays bound to the object it came from, which is why shout() needs no argument. Point.new refers to the unnamed constructor; a named one would be Point.origin.

TypeScript Tear-offs as plain function values (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Function equality and the Function type

You can declare a variable with the bare type Function, but it throws away the parameter and return types, so calls are not checked. Prefer a specific function type or a typedef. Two function values are equal only when they are the same object, with one useful exception: tear-offs of the same top-level function or static method compare equal.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the type String Function(int) describe?

    The return type comes first, then Function, then the parameter types in parentheses.
  2. 2. What is a closure?

    A closure keeps access to the variables it captured, even after the scope that created them has finished.
  3. 3. In final a = makeCounter(); final b = makeCounter();, how are the counters related?

    Every call to makeCounter creates a new count, and each returned closure captures its own.
  4. 4. What is a tear-off?

    Writing print instead of print() produces the function itself, which you can pass around, as in names.forEach(print).
  5. 5. What does typedef Predicate<T> = bool Function(T value); create?

    A typedef is an alias for an existing type, here a function type that takes a T and returns a bool.

Summary

  • Functions are objects: store them, pass them and return them.
  • Function types are written ReturnType Function(ParameterTypes).
  • Anonymous functions (x) => ... are everywhere in collection and callback code.
  • Closures capture variables, not copies, and keep them alive; each creation gets fresh variables.
  • typedef gives a function type (or any type) a readable name, and can be generic.
  • Tear-offs (print, int.parse, Point.new) pass existing functions without wrapper lambdas.

Next: lists.