Lambdas and closures

suggest change

In Dart, functions are objects. You can store them in variables, put them in collections, pass them to other functions and return them from functions. A function without a name is called an anonymous function or a lambda. When a function uses variables from the scope it was defined in, it is a closure: it keeps those variables alive and keeps access to them after the scope has ended.

This article covers:

The examples were run with Dart 3.13. For the basics of declaring functions see Functions and Function scoping.

Lambda syntax

A lambda looks like a function declaration without the return type and the name: a parameter list followed by a body. The body is either a block in {} or an arrow => followed by a single expression:

void main() {
  // Block body: any number of statements, explicit return.
  var square = (int x) {
    final result = x * x;
    return result;
  };

  // Arrow body: a single expression, returned automatically.
  var cube = (int x) => x * x * x;

  // No parameters.
  var greet = () => 'hello';

  print(square(4));
  print(cube(3));
  print(greet());
  print(square.runtimeType);
  print(greet.runtimeType);

  // Calling a lambda immediately.
  final answer = (() => 6 * 7)();
  print(answer);
}

Output:

16
27
hello
(int) => int
() => String
42

=> expr is shorthand for { return expr; }. It works for lambdas and for named functions, methods and getters. The arrow body must be a single expression, so you can't put statements like if or for loops in it; use a conditional expression a ? b : c or switch to a block body.

runtimeType shows the function's type, such as (int) => int. Lambdas get their return type inferred from the body.

Type inference for parameters

Most lambdas are written as arguments to other functions. In that case you rarely need to write parameter types, because Dart infers them from the type the function parameter expects:

void main() {
  final names = ['christopher', 'alice', 'bob'];

  // Parameter types are inferred from the context: s is a String.
  final upper = names.map((s) => s.toUpperCase()).toList();
  print(upper);

  names.sort((a, b) => a.length.compareTo(b.length));
  print(names);

  // Without a context, an untyped parameter is dynamic.
  var twice = (x) => x * 2;
  print(twice.runtimeType);
  print(twice(21));
  print(twice('ab'));

  // Give it a type and the compiler checks the calls.
  int Function(int) twiceInt = (x) => x * 2;
  print(twiceInt.runtimeType);
}

Output:

[CHRISTOPHER, ALICE, BOB]
[bob, alice, christopher]
(dynamic) => dynamic
42
abab
(int) => int

names.map(...) expects a String Function(String)-like argument, so s is a String and s.toUpperCase() is checked by the compiler. sort expects int Function(String, String), so a and b are strings.

A lambda assigned to var has no such context. Its untyped parameter becomes dynamic, which means no static checks: twice('ab') compiles and quietly returns 'abab'. When you store a lambda in a variable, either type its parameters ((int x) => x * 2) or declare the variable with a function type.

Function types and typedef

A function type is written as ReturnType Function(ParameterTypes). Parameter names are optional in the type and serve as documentation. Long function types are easier to read with a typedef:

typedef Predicate<T> = bool Function(T value);
typedef BinaryOp = int Function(int a, int b);

int combine(List<int> values, int initial, BinaryOp op) {
  var acc = initial;
  for (final v in values) {
    acc = op(acc, v);
  }
  return acc;
}

List<T> keep<T>(List<T> items, Predicate<T> test) =>
    [for (final item in items) if (test(item)) item];

void main() {
  final nums = [1, 2, 3, 4, 5];
  print(combine(nums, 0, (a, b) => a + b));
  print(combine(nums, 1, (a, b) => a * b));
  print(keep(nums, (n) => n.isOdd));
  print(keep(['a', 'bb', 'ccc'], (s) => s.length > 1));

  // Function types with optional and named parameters.
  String Function(String, [int]) repeat = (s, [n = 2]) => s * n;
  String Function({required String name, String greeting}) hello =
      ({required name, greeting = 'Hi'}) => '$greeting, $name!';
  print(repeat('ab'));
  print(repeat('ab', 3));
  print(hello(name: 'Ann'));
  print(hello(name: 'Ann', greeting: 'Hello'));

  finish();
  finish(onDone: () => print('done'));
}

// Optional callback: a nullable function type.
void finish({void Function()? onDone}) {
  print('finishing');
  onDone?.call();
}

Output:

15
120
[1, 3, 5]
[bb, ccc]
abab
ababab
Hi, Ann!
Hello, Ann!
finishing
finishing
done

Notes:

Tear-offs

You don't need a lambda to pass an existing function. Using a function's name without calling it creates a tear-off, a function object you can pass around:

class Greeter {
  final String greeting;
  Greeter(this.greeting);
  String greet(String name) => '$greeting, $name';
}

class Point {
  final int x, y;
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  @override
  String toString() => 'Point($x, $y)';
}

bool isEven(int n) => n.isEven;

void main() {
  final nums = [1, 2, 3, 4];

  // Top-level function tear-off.
  print(nums.where(isEven).toList());

  // Instance method tear-off: remembers its receiver.
  final g = Greeter('Hello');
  final greet = g.greet;
  print(['Ann', 'Bob'].map(greet).toList());

  // Static and core library methods.
  print(['1', '2', '3'].map(int.parse).toList());
  ['a', 'b'].forEach(print);

  // Constructor tear-offs.
  final makePoint = Point.new;
  final origin = Point.origin;
  print(makePoint(1, 2));
  print(origin());
  print([1, 2, 3].map((i) => Point(i, i * i)).toList());

  // Generic function instantiation.
  T first<T>(List<T> list) => list.first;
  int Function(List<int>) firstInt = first;
  print(firstInt([7, 8]));
  print(firstInt.runtimeType);
}

Output:

[2, 4]
[Hello, Ann, Hello, Bob]
[1, 2, 3]
a
b
Point(1, 2)
Point(0, 0)
[Point(1, 1), Point(2, 4), Point(3, 9)]
7
(List<int>) => int

Kinds of tear-offs:

Prefer a tear-off over a lambda that only forwards its arguments: map(int.parse) instead of map((s) => int.parse(s)). The unnecessary_lambdas lint flags such lambdas. Note that int.parse also has an optional radix parameter; a tear-off works as long as its signature is compatible with the expected type.

Closures

A lambda (or a local function) can use any variable visible where it is defined. It captures that variable and keeps it alive after the enclosing function returns:

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

void main() {
  final a = makeCounter();
  final b = makeCounter();
  print(a());
  print(a());
  print(a());
  print(b());
}

Output:

1
2
3
1

Each call to makeCounter creates a new count variable, so counters a and b are independent. Nothing outside the closure can touch count: this is a simple way to have private state without a class.

Dart closures capture variables, not their values at the time the closure was created. If the variable changes, the closure sees the change, and the closure can change it too:

void main() {
  var message = 'before';
  final show = () => print(message);

  show();
  message = 'after'; // the closure sees the new value
  show();

  // A closure can also modify the variable.
  var total = 0;
  [1, 2, 3, 4].forEach((n) => total += n);
  print(total);

  // Two closures created in the same scope share the variable.
  var balance = 100;
  void deposit(int amount) => balance += amount;
  int read() => balance;
  deposit(50);
  deposit(25);
  print(read());
}

Output:

before
after
10
175

deposit and read are local functions, which are closures just like lambdas. They share the same balance variable.

Closures in loops

Capturing variables is what makes loops interesting. Dart creates a fresh loop variable for each iteration of a for and for-in loop, so every closure remembers its own value. A variable declared outside the loop is a single variable, shared by all closures:

void main() {
  // Each iteration of a C-style for loop gets a fresh copy of i.
  final fromFor = <void Function()>[];
  for (var i = 0; i < 3; i++) {
    fromFor.add(() => print('for: $i'));
  }
  for (final f in fromFor) {
    f();
  }

  // for-in also creates a new variable per iteration.
  final fromForIn = <void Function()>[];
  for (final name in ['a', 'b', 'c']) {
    fromForIn.add(() => print('for-in: $name'));
  }
  for (final f in fromForIn) {
    f();
  }

  // A variable declared outside the loop is shared by all closures.
  final fromWhile = <void Function()>[];
  var j = 0;
  while (j < 3) {
    fromWhile.add(() => print('while: $j'));
    j++;
  }
  for (final f in fromWhile) {
    f();
  }

  // Fix: copy the value into a variable scoped to the loop body.
  final fixed = <void Function()>[];
  var k = 0;
  while (k < 3) {
    final current = k;
    fixed.add(() => print('fixed: $current'));
    k++;
  }
  for (final f in fixed) {
    f();
  }
}

Output:

for: 0
for: 1
for: 2
for-in: a
for-in: b
for-in: c
while: 3
while: 3
while: 3
fixed: 0
fixed: 1
fixed: 2

This is different from JavaScript's var, where all closures created in a for loop share one variable (and print 3 three times). In Dart, the for loop behaves like JavaScript's let.

When you use while, or update an outer variable, copy the value into a variable declared inside the loop body, as in the last loop.

Functions that return functions

A function that takes or returns other functions is called a higher-order function. Returning a closure is a common way to configure behavior once and use it many times:

int Function(int) adder(int n) => (x) => x + n;

int Function(int) multiplier(int n) {
  return (x) => x * n;
}

// Compose two functions: compose(f, g)(x) == f(g(x)).
C Function(A) compose<A, B, C>(C Function(B) f, B Function(A) g) =>
    (x) => f(g(x));

void main() {
  final add10 = adder(10);
  final triple = multiplier(3);
  print(add10(5));
  print(triple(5));

  final addThenTriple = compose(triple, add10);
  final tripleThenAdd = compose(add10, triple);
  print(addThenTriple(1));
  print(tripleThenAdd(1));

  // Building a pipeline from a list of functions.
  final steps = <int Function(int)>[add10, triple, (x) => x - 1];
  final pipeline = steps.reduce((f, g) => (x) => g(f(x)));
  print(pipeline(2));

  // Currying.
  int Function(int) Function(int) curriedAdd = (a) => (b) => a + b;
  print(curriedAdd(3)(4));
}

Output:

15
15
33
13
35
7

Memoization and run-once

Because a closure has its own private state, it's a natural fit for wrappers like a cache or a run-once guard:

R Function(A) memoize<A, R>(R Function(A) f) {
  final cache = <A, R>{};
  return (arg) => cache.putIfAbsent(arg, () => f(arg));
}

int slowSquare(int n) {
  print('computing $n');
  return n * n;
}

void main() {
  final fastSquare = memoize(slowSquare);
  print(fastSquare(4));
  print(fastSquare(4));
  print(fastSquare(5));

  // once: run an action at most one time.
  void Function() once(void Function() action) {
    var called = false;
    return () {
      if (called) return;
      called = true;
      action();
    };
  }

  final init = once(() => print('initialized'));
  init();
  init();
  init();
}

Output:

computing 4
16
16
computing 5
25
initialized

memoize keeps a Map that only the returned closure can see. once is a local function declared inside main, to show that local functions can return closures too; they can be declared anywhere a statement can go. For memoizing recursive functions see Recursion.

Recursive lambdas

A local function can call itself. A lambda assigned to a variable can't use that variable in its own initializer, because the variable isn't defined yet. Declare the variable late first or, simpler, use a local function:

void main() {
  // A local function can call itself.
  int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);
  print(fib(20));

  // A lambda assigned to a variable can't refer to itself in its
  // own initializer; declare it late (or use a local function).
  late final int Function(int) fact;
  fact = (n) => n <= 1 ? 1 : n * fact(n - 1);
  print(fact(10));
}

Output:

6765
3628800

Lambdas with collections

Collection methods are where you'll write most lambdas. They take predicates, transformations, comparators and callbacks for missing values:

void main() {
  final words = ['kiwi', 'apple', 'fig', 'banana', 'cherry'];

  print(words.where((w) => w.length > 4).toList());
  print(words.map((w) => w.length).toList());
  print(words.any((w) => w.startsWith('f')));
  print(words.every((w) => w.isNotEmpty));
  print(words.firstWhere((w) => w.contains('an')));
  print(words.firstWhere((w) => w.length > 10, orElse: () => 'none'));
  print(words.fold<int>(0, (sum, w) => sum + w.length));
  print(words.reduce((a, b) => a.length >= b.length ? a : b));
  print(words.expand((w) => [w, w.length]).take(4).toList());

  final sorted = [...words]..sort((a, b) => b.compareTo(a));
  print(sorted);

  final byLength = <int, List<String>>{};
  for (final w in words) {
    byLength.putIfAbsent(w.length, () => []).add(w);
  }
  print(byLength);

  final counts = <String, int>{};
  for (final c in 'mississippi'.split('')) {
    counts.update(c, (n) => n + 1, ifAbsent: () => 1);
  }
  print(counts);
}

Output:

[apple, banana, cherry]
[4, 5, 3, 6, 6]
true
true
banana
none
24
banana
[kiwi, 4, apple, 5]
[kiwi, fig, cherry, banana, apple]
{4: [kiwi], 5: [apple], 3: [fig], 6: [banana, cherry]}
{m: 1, i: 4, s: 4, p: 2}

See Map each element in the collection, Filter a list and Sorting for more.

forEach versus for

forEach with a lambda works, but a for-in loop is usually better: it can use await, break, continue and return from the enclosing function, and the avoid_function_literals_in_foreach_calls lint (part of the recommended lints) suggests it. Passing a tear-off is fine: list.forEach(print).

Ignoring parameters with _

Since Dart 3.7, a parameter named _ is a wildcard: it doesn't declare a variable, and you can use it for several parameters of the same function:

void main() {
  final pairs = {'a': 1, 'b': 2};

  // Since Dart 3.7, _ is a wildcard: it doesn't bind a name and can be
  // repeated for every parameter you want to ignore.
  pairs.forEach((_, value) => print(value));

  final constant = (_, _) => 0;
  print(constant(1, 2));

  final indexes = List.generate(3, (i) => i * 10);
  final zeros = List.generate(3, (_) => 0);
  print(indexes);
  print(zeros);
}

Output:

1
2
0
[0, 10, 20]
[0, 0, 0]

Before 3.7 you had to write (_, __) => 0, because _ was an ordinary name and couldn't be declared twice.

Async lambdas and callbacks

A lambda can be async. It then returns a Future. Closures are also how you give work to timers, streams and retry helpers:

import 'dart:async';

Future<void> main() async {
  var attempts = 0;

  Future<String> fetch() async {
    attempts++;
    await Future.delayed(const Duration(milliseconds: 10));
    if (attempts < 3) throw Exception('failed attempt $attempts');
    return 'data after $attempts attempts';
  }

  Future<T> retry<T>(Future<T> Function() action, int maxTries) async {
    for (var i = 1; ; i++) {
      try {
        return await action();
      } catch (e) {
        print('error: $e');
        if (i == maxTries) rethrow;
      }
    }
  }

  print(await retry(fetch, 5));

  // Timers and stream callbacks are closures too.
  var ticks = 0;
  final done = Completer<void>();
  Timer.periodic(const Duration(milliseconds: 20), (timer) {
    ticks++;
    print('tick $ticks');
    if (ticks == 3) {
      timer.cancel();
      done.complete();
    }
  });
  await done.future;

  final squares = Stream.fromIterable([1, 2, 3]).map((n) => n * n);
  await squares.forEach((n) => print('square: $n'));

  // Async lambdas return a Future.
  final load = (int id) async {
    await Future.delayed(const Duration(milliseconds: 5));
    return 'item $id';
  };
  print(load.runtimeType);
  print(await Future.wait([1, 2, 3].map(load)));
}

Output:

error: Exception: failed attempt 1
error: Exception: failed attempt 2
data after 3 attempts
tick 1
tick 2
tick 3
square: 1
square: 4
square: 9
(int) => Future<String>
[item 1, item 2, item 3]

More on async code in Async and Await and Converting callbacks to Futures.

Callable classes

A class with a call method can be invoked like a function. This is useful when a function needs configuration or several helper fields:

class Multiplier {
  final int factor;
  const Multiplier(this.factor);

  int call(int x) => x * factor;
}

class Validator {
  final List<String? Function(String)> _rules;
  Validator(this._rules);

  List<String> call(String input) => [
    for (final rule in _rules)
      if (rule(input) case final error?) error,
  ];
}

void main() {
  const doubler = Multiplier(2);
  print(doubler(21));
  print([1, 2, 3].map(doubler.call).toList());

  int Function(int) f = doubler; // implicit .call tear-off
  print(f(5));

  final validate = Validator([
    (s) => s.isEmpty ? 'must not be empty' : null,
    (s) => s.length < 8 ? 'must be at least 8 characters' : null,
    (s) => s.contains(RegExp(r'\d')) ? null : 'must contain a digit',
  ]);
  print(validate('secret'));
  print(validate('secret123'));
}

Output:

42
[2, 4, 6]
10
[must be at least 8 characters, must contain a digit]
[]

An instance of a callable class is not itself a function, but Dart inserts a .call tear-off when you assign it to a function type, as in int Function(int) f = doubler. When passing it to a generic method like map, write doubler.call explicitly.

Validator stores a list of lambdas, each returning an error message or null, and the if-case in the collection literal keeps only the non-null ones.

Capturing this

A lambda written inside an instance method can use fields and methods directly. It captures this, the whole object:

class Counter {
  int value = 0;

  // The lambda captures `this`, so it sees and changes the field.
  void Function() incrementer() => () => value++;
}

class Report {
  final List<int> data = List.filled(1000000, 0);
  final String title = 'Q3';

  // Captures `this`: keeps the whole object (and its big list) alive.
  String Function() titleGetter() => () => title;

  // Captures only the string.
  String Function() titleGetterLean() {
    final t = title;
    return () => t;
  }
}

void main() {
  final c = Counter();
  final inc = c.incrementer();
  inc();
  inc();
  print(c.value);

  final r = Report();
  print(r.titleGetter()());
  print(r.titleGetterLean()());
}

Output:

2
Q3
Q3

A closure keeps everything it captures reachable. titleGetter() keeps the entire Report, including its one-million-element list, alive for as long as the closure exists, even though it only needs title. If a long-lived callback (a listener, a cache, a timer) needs only a small part of an object, copy that part into a local variable first, as in titleGetterLean. See Memory and garbage collection.

Equality of functions

Tear-offs of the same method on the same object are equal, and tear-offs of the same top-level or static function are equal. Two lambdas are never equal, even with identical code, because each evaluation of a lambda expression creates a new function object. This matters for APIs that remove callbacks:

class Button {
  final _listeners = <void Function()>[];
  void addListener(void Function() f) => _listeners.add(f);
  void removeListener(void Function() f) => _listeners.remove(f);
  void click() {
    for (final f in _listeners) {
      f();
    }
  }
  int get listenerCount => _listeners.length;
}

class Logger {
  void onClick() => print('clicked');
}

void main() {
  final logger = Logger();

  // Tear-offs of the same method on the same object are equal.
  print(logger.onClick == logger.onClick);

  // Two lambdas with identical code are different objects.
  final a = () => print('clicked');
  final b = () => print('clicked');
  print(a == b);
  print(a == a);

  final button = Button();
  button.addListener(logger.onClick);
  button.removeListener(logger.onClick);
  print(button.listenerCount);

  button.addListener(() => print('hi'));
  button.removeListener(() => print('hi')); // removes nothing
  print(button.listenerCount);

  // Keep a reference if you need to remove a lambda later.
  void handler() => print('handler');
  button.addListener(handler);
  button.removeListener(handler);
  print(button.listenerCount);
}

Output:

true
false
true
0
1
1

removeListener(() => print('hi')) creates a brand new function that was never added, so nothing is removed. Store the function in a variable or use a method tear-off when you need to unregister it later. The same applies to Flutter's addListener / removeListener and to Stream subscriptions (keep the StreamSubscription and cancel it).

Pitfalls

=> { creates a set or map

Coming from JavaScript, it's easy to write (x) => { ... }. In Dart, the braces after => are a set or map literal, not a block:

void main() {
  // Looks like a block body, but it's an arrow returning a Set literal.
  final wrong = (int x) => {x * 2};
  print(wrong(5));
  print(wrong(5).runtimeType);

  // Correct: either an arrow with a bare expression...
  final arrow = (int x) => x * 2;
  // ...or a block body with return.
  final block = (int x) {
    return x * 2;
  };
  print(arrow(5));
  print(block(5));
}

Output:

{10}
_Set<int>
10
10

(int x) => {x * 2} returns the set {10}. With a void context such as forEach((n) => {print(n)}), the code even appears to work. The unnecessary_set_literal lint warns about the second case. Use either => without braces or { ... } without the arrow, never both.

Calling instead of passing

Pass the function, not the result of calling it:

void save() => print('saved');

void run(void Function() action) {
  print('running');
  action();
}

void main() {
  run(save); // pass the function
  run(() => save()); // same thing, extra wrapper
  // run(save()); // error: save() returns void, not a function
}

Output:

running
saved
running
saved

Uncommenting run(save()) fails to compile:

error - This expression has a type of 'void' so its value can't be used. - use_of_void_result

If the function returns a value instead of void, the mistake can produce a confusing type error or, worse, call the function immediately at the wrong time. This is a common bug in Flutter code: onPressed: submit() instead of onPressed: submit.

Untyped lambdas in variables

As shown above, var f = (x) => ... makes x dynamic. Type the parameters or the variable.

Mutating captured variables from async callbacks

A closure sees the current value of a captured variable when it runs, not when it was created. A callback scheduled with Future.delayed, Timer or a stream listener that reads a variable you keep changing will see whatever value the variable has at that later time. Copy the value into a final local before scheduling the callback if you need the value from that moment.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents