DartBasic 2 min read

Dart callbacks and typedefs: inject a notification action

Pass behavior through a typed callback instead of coupling a workflow to one output channel.

On this page

An order workflow may notify a screen, a test recorder or a console logger. A callback lets the workflow communicate through a small contract without importing every possible output system. Use a typedef when naming that contract improves the call site.

Worked example

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

main.dart
typedef Notify = void Function(String message);

void confirmOrder(String orderId, {required Notify notify}) {
  if (orderId.isEmpty) throw ArgumentError('Order ID is required.');
  notify('Confirmed $orderId');
}

void main() {
  final messages = <String>[];
  confirmOrder('ORD-42', notify: messages.add);
  print(messages.single);
  confirmOrder('ORD-43', notify: print);
}

Follow the data and control flow

The workflow calls notify after validation. messages.add is a method tear-off: it passes a compatible function value without calling it immediately. The test-like recorder observes the message independently of a user interface.

An asynchronous callback needs a contract such as Future<void> Function(String) and a caller that awaits it when completion matters. Merely changing the implementation to async without updating the contract can make failures easy to lose.

A mistake to avoid

Passing notify: messages.add('text') calls the method now and passes its result instead of the function. Also avoid a callback with several unrelated responsibilities; a small interface is often clearer when a dependency exposes several coordinated operations.

Practice and verification

Add a callback that records both a message and the current order count. Then create an async variant and verify that confirmation waits for notification completion. Explain whether a notification failure should undo an already-confirmed business operation.

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.