Skip to content
Blog

Capturing Variables with Closures and Function Tear-Offs in Dart

Learn how Dart closures capture variables by reference, how loop closures bind per iteration, and how tear-offs replace redundant lambdas in Dart.

Published on • December 3, 2026

AI Assistant

Dart decides a variable’s scope from the layout of the code itself, which means a function can outlive the block that created it and still remember everything it saw. That remembered environment is a closure — and once you see how it works, callbacks, event handlers, and everyday one-liners stop feeling like magic.

Lexical scope: follow the curly braces outwards

Dart is lexically scoped: to find out whether a variable is visible at some point in the program, follow the curly braces outwards from that point until you reach the declaration. A nested function can therefore use variables from every enclosing scope, all the way up to the top level.

bool topLevel = true;

void main() {
  var insideMain = true;
  void nestedFunction() {
    var insideFunction = true;
    assert(topLevel && insideMain && insideFunction);
  }
  nestedFunction();
}

The interesting part begins when a function escapes that environment entirely: the closure keeps the environment with it.

Closures capture variables, not values

A closure is a function object that can access variables in its lexical scope even when the function itself is used outside that scope. The classic example is makeAdder, which returns a small function that remembers its addBy argument wherever it goes:

int Function(int) makeAdder(int addBy) => (int i) => addBy + i;

void main() {
  final add2 = makeAdder(2);
  final add4 = makeAdder(4);
  assert(add2(3) == 5);
  assert(add4(3) == 7);
}

Each call to makeAdder creates a fresh addBy variable, and each returned closure carries its own. The closure does not copy the value once and forget the variable — it keeps a reference to the variable itself. That distinction becomes obvious when the captured variable is mutable:

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

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

count never appears in main(), yet every call to tick() sees the previous calls’ writes. Two closures created in the same scope share that one variable, so a mutation made through one — say, score += points in a local addPoints helper — is immediately visible through the other.

Closures in loops

Because a closure captures the variable, loops deserve a closer look. Each iteration of a Dart for loop binds a fresh copy of the loop variable, so closures created inside the loop do not all race to the final value — each one sees the value from its own iteration:

void main() {
  final actions = <void Function()>[];
  for (var i = 0; i < 3; i++) {
    actions.add(() => print('tick $i'));
  }
  for (final action in actions) {
    action();
  }
  // tick 0, tick 1, tick 2
}

If you are coming from a language where loop closures share one variable, this is worth internalizing before you start hoisting callbacks out of loops. For the rest of Dart’s loop shapes, iteration order, and scoping rules, see dart-for-while-do-while-loops.md.

Closures as callbacks and event handlers

Closures shine whenever a function needs to run later, with context it never received as a parameter. Register a lambda on an object today, invoke it tomorrow, and the surrounding state travels with it:

class Button {
  void Function()? onPressed;
  void tap() => onPressed?.call();
}

void main() {
  final button = Button();
  var clicks = 0;
  button.onPressed = () {
    clicks++;
    print('clicks: $clicks');
  };
  button.tap();
  button.tap(); // clicks: 2
}

The handler captures clicks from main(), so the counter survives between taps. The same pattern powers sort comparators, where filters, and debounce timers: the lambda carries the surrounding state along with the code, which is exactly why a callback registered on a long-lived object deserves some scrutiny.

Memory: closures keep their environment alive

A closure keeps every captured variable alive for as long as the closure itself is reachable. Usually that is precisely what you want, but it has consequences worth knowing:

  • A callback registered on a long-lived object (an app-wide stream, a singleton) keeps its whole captured scope alive, even after the local function has “returned”.
  • Capturing a large object in a tiny lambda pins that entire object in memory until the closure itself is collected.
  • Dropping the last reference to the closure releases the captured variables with it — Dart’s garbage collector handles this automatically, so capture just the piece you need (final name = user.name;) rather than a whole object graph.

Function tear-offs

When you refer to a function, method, or named constructor without parentheses, Dart creates a tear-off. It is a closure that takes the same parameters as the underlying function and invokes that function when called:

void main() {
  final charCodes = [68, 97, 114, 116];
  final buffer = StringBuffer();
  charCodes.forEach(print); // function tear-off
  charCodes.forEach(buffer.write); // method tear-off
  final words = charCodes.map(String.fromCharCode).toList();
  print(words.join(' ')); // Dart
  print(buffer.toString()); // 6897114116
}

Compare the two styles directly, and Effective Dart’s rule becomes obvious:

ScenarioLambda wrapperTear-off
Invoke a top-level function(code) => print(code)print
Invoke a method on an object(code) => buffer.write(code)buffer.write
Invoke a named constructor(code) => String.fromCharCode(code)String.fromCharCode
Invoke an unnamed constructor(code) => StringBuffer(code)StringBuffer.new
Needs extra logic or extra argumentsRequiredNot possible

The guideline is blunt: DON’T create a lambda when a tear-off will do (the unnecessary_lambdas lint). A tear-off says exactly what it does, skips the wrapper allocation, and can never accidentally capture the wrong thing — and it works for constructor tear-offs like StringBuffer.new too, as dart-named-factory-redirecting-constructors.md shows.

When closures are equal

Function objects support ==, and the rules follow from what the closure refers to. Top-level functions and static methods tear off to equal objects no matter where you reference them — assert(foo == foo) and assert(A.bar == A.bar) both hold. Instance method tear-offs compare equal only when they come from the same instance, because the receiver is part of the closure’s captured state: first.baz == first.baz is true, while first.baz != second.baz for two different A() objects. There is a companion rule for when a closure genuinely needs a name: DO use a function declaration to bind a function to a name (prefer_function_declarations_over_variables) rather than assigning a lambda to a variable — void logName(String name) => print(name); reads and analyzes better than final logName = (String name) => print(name);. Reserve lambdas for the case where the function is used immediately and never needs to be referred to again.

Takeaways

  • Scope is lexical: follow the curly braces outwards to see what a function can see.
  • Closures capture variables by reference, so mutable captured state is shared and persists across calls.
  • Dart binds a fresh loop variable per iteration, so closures created in a loop capture per-iteration values.
  • Closures keep their captured environment alive; be deliberate about what a long-lived callback holds.
  • Takeaway: capture deliberately and tear off instead of wrapping — closures and tear-offs are one mechanism used at two different levels of intent.

References