DartBasic 2 min read

Dart callable objects and tear-offs: configure a reusable calculation

Pass behavior without calling it early and give configured operations a clear owner.

On this page

A small strategy sometimes needs configuration and behavior together. A callable object exposes a call method so an instance can be invoked like an operation. A tear-off instead passes an existing function or constructor as a value.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
class AddDeliveryFee {
  AddDeliveryFee(this.feePaise);
  final int feePaise;
  int call(int subtotalPaise) => subtotalPaise + feePaise;
}

class Quantity {
  Quantity(this.value);
  final int value;
}

void main() {
  final priceWithFee = AddDeliveryFee(2500);
  print(priceWithFee(10000));
  final quantities = [1, 2, 3].map(Quantity.new).toList();
  print(quantities.last.value);
}

Follow the data and control flow

The object retains one fee and applies it when invoked. The map receives the constructor tear-off Quantity.new, allowing each integer to become an instance when the iterable is consumed. Passing a tear-off is different from invoking a constructor immediately.

Use a closure when one captured value is enough. Use an object when the operation benefits from named configuration, additional methods or an explicit lifecycle. For a callback requiring a function type, pass the specific method tear-off that matches the contract.

A mistake to avoid

A callable object is still an object with state. Validate its configuration and avoid hiding I/O inside a call that looks like a pure price calculation. Do not add parentheses to a tear-off unless you intend to call it at that point.

Practice and verification

Validate non-negative fees and totals. Pass priceWithFee.call into a typed transformation and compare it with a closure. Explain why a calculation and an HTTP request should have different completion contracts.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.