Design patterns

suggest change

Design patterns are named solutions to problems that come up again and again in object-oriented code. Most of the classic patterns from the "Gang of Four" book were written for C++ and Smalltalk in 1994. Dart has features those languages lacked: first-class functions, factory constructors, cascades, named parameters, mixins, streams, generators, sealed classes and pattern matching. As a result, many patterns in Dart shrink to a language feature or a few lines of code.

This article goes through the most useful patterns and shows the idiomatic Dart version of each:

The examples were run with Dart 3.13. Each one is a complete program you can save to a file and run with dart run file.dart.

Factory

A factory decides which object to create, so the caller doesn't have to. In Java you'd write a static create method or a separate factory class. In Dart, a factory constructor does the job: it looks like a normal constructor to the caller, but it can return an instance of a subtype, or an existing instance.

Here Shape.fromJson uses map patterns to inspect the data and returns a Circle or a Rect:

sealed class Shape {
  const Shape();

  // Factory constructor: picks the concrete class from the data.
  factory Shape.fromJson(Map<String, Object?> json) {
    return switch (json) {
      {'type': 'circle', 'r': num r} => Circle(r.toDouble()),
      {'type': 'rect', 'w': num w, 'h': num h} =>
        Rect(w.toDouble(), h.toDouble()),
      _ => throw FormatException('unknown shape: $json'),
    };
  }

  double get area;
}

class Circle extends Shape {
  final double r;
  const Circle(this.r);
  @override
  double get area => 3.14159 * r * r;
  @override
  String toString() => 'Circle($r)';
}

class Rect extends Shape {
  final double w, h;
  const Rect(this.w, this.h);
  @override
  double get area => w * h;
  @override
  String toString() => 'Rect($w x $h)';
}

void main() {
  final data = [
    {'type': 'circle', 'r': 2},
    {'type': 'rect', 'w': 3, 'h': 4.5},
  ];
  for (final json in data) {
    final shape = Shape.fromJson(json);
    print('$shape area=${shape.area.toStringAsFixed(2)}');
  }
  try {
    Shape.fromJson({'type': 'hexagon'});
  } on FormatException catch (e) {
    print(e.message);
  }
}

Output:

Circle(2.0) area=12.57
Rect(3.0 x 4.5) area=13.50
unknown shape: {type: hexagon}

The caller writes Shape.fromJson(json) and gets back a Shape; it never mentions Circle or Rect. Because Shape is sealed, code that later switches over shapes gets exhaustiveness checking (see Pattern matching).

A factory constructor can also return a cached object instead of creating a new one. The real constructor is private (Color._), so every color has to go through the factory:

class Color {
  final int r, g, b;

  static final _cache = <String, Color>{};

  const Color._(this.r, this.g, this.b);

  // Returns a cached instance instead of always allocating a new one.
  factory Color.hex(String hex) {
    return _cache.putIfAbsent(hex, () {
      print('  parsing $hex');
      final v = int.parse(hex.replaceFirst('#', ''), radix: 16);
      return Color._((v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff);
    });
  }

  @override
  String toString() => 'Color($r, $g, $b)';
}

void main() {
  final a = Color.hex('#ff8800');
  final b = Color.hex('#ff8800');
  print(a);
  print(identical(a, b));
}

Output:

  parsing #ff8800
Color(255, 136, 0)
true

The string was parsed only once, and both variables refer to the same object. The Logger(name) constructor in package:logging works the same way. More on factory and named constructors in Constructors.

Builder

The builder pattern exists to avoid constructors with a long list of positional parameters, where it's easy to swap two arguments. In Dart, named parameters with default values solve most of that problem directly:

class ServerConfig {
  final String host;
  final int port;
  final bool tls;
  final int maxConnections;

  const ServerConfig({
    this.host = 'localhost',
    this.port = 8443,
    this.tls = true,
    this.maxConnections = 100,
  }) : assert(port > 0 && port < 65536);

  ServerConfig copyWith({String? host, int? port, bool? tls, int? maxConnections}) =>
      ServerConfig(
        host: host ?? this.host,
        port: port ?? this.port,
        tls: tls ?? this.tls,
        maxConnections: maxConnections ?? this.maxConnections,
      );

  @override
  String toString() => 'ServerConfig($host:$port, tls: $tls, max: $maxConnections)';
}

void main() {
  const defaults = ServerConfig();
  final prod = ServerConfig(host: '0.0.0.0', maxConnections: 1000);
  final dev = prod.copyWith(tls: false, port: 9000);
  print(defaults);
  print(prod);
  print(dev);
}

Output:

ServerConfig(localhost:8443, tls: true, max: 100)
ServerConfig(0.0.0.0:8443, tls: true, max: 1000)
ServerConfig(0.0.0.0:9000, tls: false, max: 1000)

Named parameters make every call site self-documenting, defaults cover optional settings, and the object stays immutable. copyWith replaces the "modify a builder and build again" use case: you derive a new configuration from an existing one. See Copying and cloning and Immutability.

A separate builder class still makes sense when the object is assembled step by step (for example in a loop), when some steps depend on others, or when you want to validate the combination before creating the object. Dart's cascade operator .. makes builders pleasant without every method having to return this:

class HttpRequestSpec {
  final String method;
  final Uri url;
  final Map<String, String> headers;
  final String? body;
  final Duration timeout;

  HttpRequestSpec._(this.method, this.url, this.headers, this.body,
      this.timeout);

  @override
  String toString() =>
      '$method $url\n  headers: $headers\n  body: $body\n  timeout: ${timeout.inSeconds}s';
}

class RequestBuilder {
  String _method = 'GET';
  final Uri _url;
  final _headers = <String, String>{};
  String? _body;
  Duration _timeout = const Duration(seconds: 30);

  RequestBuilder(String url) : _url = Uri.parse(url);

  void method(String m) => _method = m.toUpperCase();
  void header(String name, String value) => _headers[name] = value;
  void json(String body) {
    _body = body;
    header('content-type', 'application/json');
  }

  void timeout(Duration d) => _timeout = d;

  HttpRequestSpec build() {
    if (_body != null && _method == 'GET') {
      throw StateError('GET request cannot have a body');
    }
    return HttpRequestSpec._(
        _method, _url, Map.unmodifiable(_headers), _body, _timeout);
  }
}

void main() {
  // Cascades (..) call several methods on the same builder.
  final req = (RequestBuilder('https://api.example.com/users')
        ..method('post')
        ..header('authorization', 'Bearer abc')
        ..json('{"name":"Ann"}')
        ..timeout(const Duration(seconds: 5)))
      .build();
  print(req);

  try {
    (RequestBuilder('https://example.com')..json('{}')).build();
  } on StateError catch (e) {
    print(e.message);
  }
}

Output:

POST https://api.example.com/users
  headers: {authorization: Bearer abc, content-type: application/json}
  body: {"name":"Ann"}
  timeout: 5s
GET request cannot have a body

The builder methods return void. The cascade ..method(...) calls a method and evaluates to the builder itself, so the chain works anyway. The parentheses around the cascade are needed so that .build() is called on the result of the whole cascade. StringBuffer and BytesBuilder in the core libraries are builders of this kind; see Building from parts.

Strategy

The strategy pattern lets you swap an algorithm at runtime. The classic version defines an interface with one method and a class per algorithm. In Dart, a function type is that interface, and any function or closure is a strategy:

typedef PricingStrategy = double Function(double subtotal);

double regular(double subtotal) => subtotal;
double blackFriday(double subtotal) => subtotal * 0.7;
PricingStrategy loyalty(int years) =>
    (subtotal) => subtotal * (1 - (years * 0.02).clamp(0, 0.2));

class Checkout {
  PricingStrategy pricing;
  Checkout({this.pricing = regular});

  String total(List<double> prices) {
    final subtotal = prices.fold(0.0, (a, b) => a + b);
    return pricing(subtotal).toStringAsFixed(2);
  }
}

void main() {
  final cart = [19.99, 5.01, 75.0];
  final checkout = Checkout();
  print('regular:      ${checkout.total(cart)}');
  checkout.pricing = blackFriday;
  print('black friday: ${checkout.total(cart)}');
  checkout.pricing = loyalty(3);
  print('loyal 3y:     ${checkout.total(cart)}');
  checkout.pricing = loyalty(25);
  print('loyal 25y:    ${checkout.total(cart)}');
}

Output:

regular:      100.00
black friday: 70.00
loyal 3y:     94.00
loyal 25y:    80.00

Top-level functions are passed as tear-offs (blackFriday), and loyalty(3) returns a closure that remembers its configuration. An interface with a single method is usually a sign you can use a function type instead; see Lambdas and closures. Use a class when the strategy has several related methods or needs its own state; Composition and delegation shows that version.

Adapter

An adapter makes an existing class usable through an interface it doesn't implement. You can't change the third-party class, so you wrap it in a small class that implements your interface and translates every call:

// The interface our application code is written against.
abstract interface class KeyValueStore {
  String? get(String key);
  void put(String key, String value);
}

// A third-party class with a different API that we can't change.
class LegacyCache {
  final _data = <String, List<int>>{};
  void store(String k, List<int> bytes) => _data[k] = bytes;
  List<int>? fetch(String k) => _data[k];
}

// Adapter: implements our interface by translating calls.
class LegacyCacheAdapter implements KeyValueStore {
  final LegacyCache _cache;
  LegacyCacheAdapter(this._cache);

  @override
  String? get(String key) {
    final bytes = _cache.fetch(key);
    return bytes == null ? null : String.fromCharCodes(bytes);
  }

  @override
  void put(String key, String value) => _cache.store(key, value.codeUnits);
}

void greet(KeyValueStore store) {
  store.put('name', 'Ann');
  print('hello, ${store.get('name')}');
  print('missing: ${store.get('nope')}');
}

void main() {
  greet(LegacyCacheAdapter(LegacyCache()));
}

Output:

hello, Ann
missing: null

greet only knows about KeyValueStore. Later you can replace the legacy cache with something else by writing another adapter, without touching greet. Every Dart class has an implicit interface, so you can also adapt to a concrete class with implements.

When you only want a nicer API on top of a type, without making it conform to an existing interface, Extension methods or extension types are lighter alternatives: they add methods without allocating a wrapper object.

Proxy

A proxy has the same interface as the real object and stands in for it, adding control: lazy creation, caching, access checks, logging or retries. Callers can't tell the difference.

This caching proxy sits in front of a slow service:

abstract interface class WeatherService {
  Future<double> temperature(String city);
}

class SlowWeatherApi implements WeatherService {
  int calls = 0;
  @override
  Future<double> temperature(String city) async {
    calls++;
    await Future<void>.delayed(const Duration(milliseconds: 100));
    return city.length * 2.5; // pretend this came from the network
  }
}

// Proxy: same interface, controls access to the real object.
class CachingWeatherProxy implements WeatherService {
  final WeatherService _real;
  final Duration ttl;
  final _cache = <String, (DateTime, Future<double>)>{};

  CachingWeatherProxy(this._real, {this.ttl = const Duration(minutes: 5)});

  @override
  Future<double> temperature(String city) {
    final now = DateTime.now();
    final hit = _cache[city];
    if (hit != null && now.difference(hit.$1) < ttl) return hit.$2;
    // Cache the Future, not the value, so concurrent callers share one request.
    final f = _real.temperature(city);
    _cache[city] = (now, f);
    return f;
  }
}

Future<void> main() async {
  final api = SlowWeatherApi();
  final WeatherService weather = CachingWeatherProxy(api);

  final sw = Stopwatch()..start();
  final results = await Future.wait([
    weather.temperature('Paris'),
    weather.temperature('Paris'),
    weather.temperature('Oslo'),
  ]);
  print('$results in ~${(sw.elapsedMilliseconds / 100).round() * 100}ms');
  print('again: ${await weather.temperature('Paris')}');
  print('real API calls: ${api.calls}');
}

Output:

[12.5, 12.5, 10.0] in ~100ms
again: 12.5
real API calls: 2

Two concurrent requests for Paris resulted in a single call to the real API, because the proxy caches the Future rather than the value. One caveat: a failed Future is cached too. In real code, remove the cache entry when the future completes with an error. For more caching techniques see Caching.

A proxy and a decorator are built the same way: both implement an interface and hold a reference to an object with the same interface. The difference is intent. A decorator adds behavior, a proxy controls access to the object.

Observer

In the observer pattern, an object (the subject) keeps a list of listeners and notifies them when its state changes. A minimal version needs only a list of callbacks:

typedef Listener = void Function();

// A minimal observable, similar to Flutter's ChangeNotifier.
class Observable {
  final _listeners = <Listener>[];

  void addListener(Listener l) => _listeners.add(l);
  void removeListener(Listener l) => _listeners.remove(l);

  void notifyListeners() {
    // Iterate over a copy so listeners can unsubscribe while being notified.
    for (final l in List.of(_listeners)) {
      l();
    }
  }
}

class Cart extends Observable {
  final _items = <String, int>{};

  Map<String, int> get items => Map.unmodifiable(_items);
  int get count => _items.values.fold(0, (a, b) => a + b);

  void add(String item) {
    _items.update(item, (n) => n + 1, ifAbsent: () => 1);
    notifyListeners();
  }
}

void main() {
  final cart = Cart();

  void badge() => print('badge: ${cart.count}');
  cart.addListener(badge);
  cart.addListener(() => print('items: ${cart.items}'));

  cart.add('apple');
  cart.add('apple');

  cart.removeListener(badge); // works: same function object
  cart.add('pear');
}

Output:

badge: 1
items: {apple: 1}
badge: 2
items: {apple: 2}
items: {apple: 2, pear: 1}

Flutter's ChangeNotifier is essentially this class. To remove a listener you need a reference to the same function you added, which is why badge is a named local function rather than an inline lambda.

For anything more than "something changed", use a Stream. A StreamController.broadcast() is a ready-made subject: it supports many listeners, delivers events asynchronously, lets subscribers filter and transform events, and has proper subscription cancellation:

import 'dart:async';

sealed class StockEvent {}

class PriceChanged extends StockEvent {
  final String symbol;
  final double price;
  PriceChanged(this.symbol, this.price);
}

class TradingHalted extends StockEvent {
  final String symbol;
  TradingHalted(this.symbol);
}

class StockTicker {
  final _controller = StreamController<StockEvent>.broadcast();

  Stream<StockEvent> get events => _controller.stream;

  void update(String symbol, double price) =>
      _controller.add(PriceChanged(symbol, price));
  void halt(String symbol) => _controller.add(TradingHalted(symbol));
  Future<void> close() => _controller.close();
}

Future<void> main() async {
  final ticker = StockTicker();

  final sub1 = ticker.events.listen((e) {
    switch (e) {
      case PriceChanged(:final symbol, :final price):
        print('display: $symbol = $price');
      case TradingHalted(:final symbol):
        print('display: $symbol HALTED');
    }
  });

  // A second subscriber that only cares about big prices.
  ticker.events
      .where((e) => e is PriceChanged && e.price > 200)
      .cast<PriceChanged>()
      .listen((e) => print('alert: ${e.symbol} above 200'));

  ticker.update('ACME', 120.5);
  ticker.update('ACME', 201.0);
  await Future<void>.delayed(Duration.zero);

  await sub1.cancel();
  ticker.halt('ACME');
  await ticker.close();
  print('done');
}

Output:

display: ACME = 120.5
display: ACME = 201.0
alert: ACME above 200
done

Making the event type sealed lets subscribers handle every kind of event with an exhaustive switch. After sub1.cancel() the first subscriber no longer receives events, which is why the halt message wasn't printed. Stream events are delivered asynchronously, so await Future.delayed(Duration.zero) gives listeners a chance to run before we cancel. See Async and Await.

Command

A command turns a request into an object. Once operations are objects, you can store them, queue them, log them and undo them. The textbook use is undo/redo in an editor:

class Document {
  final buffer = StringBuffer();
  @override
  String toString() => '"$buffer"';
}

abstract interface class Command {
  void execute();
  void undo();
}

class Insert implements Command {
  final Document doc;
  final String text;
  Insert(this.doc, this.text);

  @override
  void execute() => doc.buffer.write(text);

  @override
  void undo() {
    final s = doc.buffer.toString();
    doc.buffer
      ..clear()
      ..write(s.substring(0, s.length - text.length));
  }
}

class Clear implements Command {
  final Document doc;
  String _saved = '';
  Clear(this.doc);

  @override
  void execute() {
    _saved = doc.buffer.toString();
    doc.buffer.clear();
  }

  @override
  void undo() => doc.buffer.write(_saved);
}

class History {
  final _done = <Command>[];
  final _undone = <Command>[];

  void run(Command c) {
    c.execute();
    _done.add(c);
    _undone.clear(); // a new command invalidates the redo stack
  }

  bool undo() {
    if (_done.isEmpty) return false;
    final c = _done.removeLast()..undo();
    _undone.add(c);
    return true;
  }

  bool redo() {
    if (_undone.isEmpty) return false;
    final c = _undone.removeLast()..execute();
    _done.add(c);
    return true;
  }
}

void main() {
  final doc = Document();
  final history = History();

  history.run(Insert(doc, 'Hello'));
  history.run(Insert(doc, ', world'));
  print(doc);
  history.run(Clear(doc));
  print(doc);
  history.undo();
  print(doc);
  history.undo();
  print(doc);
  history.redo();
  print(doc);
  print('undo all: ${[history.undo(), history.undo(), history.undo()]}');
  print(doc);
}

Output:

"Hello, world"
""
"Hello, world"
"Hello"
"Hello, world"
undo all: [true, true, false]
""

Each command remembers what it needs to undo itself: Insert knows the text it added, Clear saves the content it removed. History keeps two stacks; running a new command clears the redo stack, as in every text editor.

If you don't need undo, a command can be just a function: a List<void Function()> is a perfectly good job queue.

State

The state pattern models an object whose behavior depends on its current state. The classic solution uses a class per state with a method for each event, and the context object delegates to the current state.

With sealed classes and pattern matching, Dart offers a clearer alternative: describe states and events as sealed hierarchies and write the transitions as a single switch over the pair (state, event):

sealed class Connection {
  const Connection();
}

class Disconnected extends Connection {
  const Disconnected();
}

class Connecting extends Connection {
  final int attempt;
  const Connecting(this.attempt);
}

class Connected extends Connection {
  final String sessionId;
  const Connected(this.sessionId);
}

class Failed extends Connection {
  final String reason;
  const Failed(this.reason);
}

sealed class Event {}

class Connect extends Event {}

class Succeeded extends Event {
  final String sessionId;
  Succeeded(this.sessionId);
}

class ConnectError extends Event {
  final String reason;
  ConnectError(this.reason);
}

class Disconnect extends Event {}

const maxAttempts = 3;

// The whole state machine is one pure function.
Connection transition(Connection state, Event event) => switch ((state, event)) {
      (Disconnected() || Failed(), Connect()) => const Connecting(1),
      (Connecting(), Succeeded(:final sessionId)) => Connected(sessionId),
      (Connecting(:final attempt), ConnectError()) when attempt < maxAttempts =>
        Connecting(attempt + 1),
      (Connecting(), ConnectError(:final reason)) => Failed(reason),
      (Connected(), Disconnect()) => const Disconnected(),
      _ => state, // ignore events that don't apply in this state
    };

String describe(Connection c) => switch (c) {
      Disconnected() => 'offline',
      Connecting(:final attempt) => 'connecting (attempt $attempt)',
      Connected(:final sessionId) => 'online, session $sessionId',
      Failed(:final reason) => 'failed: $reason',
    };

void main() {
  Connection state = const Disconnected();
  final events = [
    Connect(),
    ConnectError('timeout'),
    ConnectError('timeout'),
    ConnectError('refused'),
    Disconnect(), // ignored in Failed state
    Connect(),
    Succeeded('s-42'),
    Disconnect(),
  ];
  print(describe(state));
  for (final e in events) {
    state = transition(state, e);
    print('${e.runtimeType.toString().padRight(12)} -> ${describe(state)}');
  }
}

Output:

offline
Connect      -> connecting (attempt 1)
ConnectError -> connecting (attempt 2)
ConnectError -> connecting (attempt 3)
ConnectError -> failed: refused
Disconnect   -> failed: refused
Connect      -> connecting (attempt 1)
Succeeded    -> online, session s-42
Disconnect   -> offline

Some things to note:

For a fixed set of states without associated data, an enum is enough.

Visitor

The visitor pattern adds operations to a class hierarchy without changing the classes. Each class gets an accept method that calls back the right visit method on the visitor (double dispatch). Since Dart 3, a function with an exhaustive switch over a sealed type does the same with much less code. The example shows both:

// Classic visitor: double dispatch through accept().
abstract interface class ExprVisitor<R> {
  R visitNum(Num e);
  R visitAdd(Add e);
  R visitMul(Mul e);
}

sealed class Expr {
  R accept<R>(ExprVisitor<R> v);
}

class Num extends Expr {
  final num value;
  Num(this.value);
  @override
  R accept<R>(ExprVisitor<R> v) => v.visitNum(this);
}

class Add extends Expr {
  final Expr left, right;
  Add(this.left, this.right);
  @override
  R accept<R>(ExprVisitor<R> v) => v.visitAdd(this);
}

class Mul extends Expr {
  final Expr left, right;
  Mul(this.left, this.right);
  @override
  R accept<R>(ExprVisitor<R> v) => v.visitMul(this);
}

class Printer implements ExprVisitor<String> {
  @override
  String visitNum(Num e) => '${e.value}';
  @override
  String visitAdd(Add e) => '(${e.left.accept(this)} + ${e.right.accept(this)})';
  @override
  String visitMul(Mul e) => '${e.left.accept(this)} * ${e.right.accept(this)}';
}

// Modern Dart: a function with an exhaustive switch over the sealed type.
num evaluate(Expr e) => switch (e) {
      Num(:final value) => value,
      Add(:final left, :final right) => evaluate(left) + evaluate(right),
      Mul(:final left, :final right) => evaluate(left) * evaluate(right),
    };

// Simplification is easy with nested patterns.
Expr simplify(Expr e) => switch (e) {
      Mul(left: Num(value: 0), right: _) || Mul(left: _, right: Num(value: 0)) =>
        Num(0),
      Mul(left: Num(value: 1), :final right) => simplify(right),
      Add(left: Num(value: 0), :final right) => simplify(right),
      Add(:final left, :final right) => Add(simplify(left), simplify(right)),
      Mul(:final left, :final right) => Mul(simplify(left), simplify(right)),
      Num() => e,
    };

void main() {
  final expr = Add(Num(2), Mul(Num(3), Add(Num(0), Num(4))));
  print(expr.accept(Printer()));
  print(evaluate(expr));
  final s = simplify(Add(Num(0), Mul(Num(1), Num(7))));
  print(s.accept(Printer()));
  print(simplify(Mul(Num(5), Num(0))).accept(Printer()));
}

Output:

(2 + 3 * (0 + 4))
14
7
0

Printer is a classic visitor: it needs the ExprVisitor interface and an accept method in every class. evaluate and simplify are plain functions. They still get compile-time checking that every case is covered, and nested patterns like Mul(left: Num(value: 0), right: _) express rules that would be awkward to write with visitors.

The classic visitor is still useful when the hierarchy can't be sealed, for example when its classes are spread over several libraries, or when you publish a library and want users to add operations through a stable interface.

Template method

A template method defines the skeleton of an algorithm in a base class and lets subclasses fill in individual steps. In Dart that's an abstract class with abstract methods for the required steps and ordinary methods for optional hooks:

abstract class Report {
  // The template method: a fixed algorithm with overridable steps.
  String render(List<(String, num)> rows) {
    final out = StringBuffer();
    out.write(header());
    for (final (i, (name, value)) in rows.indexed) {
      out.write(row(i, name, value));
    }
    if (showTotal) {
      out.write(footer(rows.fold<num>(0, (sum, r) => sum + r.$2)));
    }
    return out.toString();
  }

  String header();
  String row(int index, String name, num value);
  String footer(num total) => '';

  // A hook with a default that subclasses may override.
  bool get showTotal => true;
}

class TextReport extends Report {
  @override
  String header() => 'Item        Amount\n';
  @override
  String row(int index, String name, num value) =>
      '${name.padRight(10)}${value.toString().padLeft(8)}\n';
  @override
  String footer(num total) => '${'TOTAL'.padRight(10)}${'$total'.padLeft(8)}\n';
}

class CsvReport extends Report {
  @override
  String header() => 'index,name,value\n';
  @override
  String row(int index, String name, num value) => '$index,$name,$value\n';
  @override
  bool get showTotal => false;
}

void main() {
  final rows = [('coffee', 12), ('bagel', 4.5), ('juice', 6)];
  print(TextReport().render(rows));
  print(CsvReport().render(rows));
}

Output:

Item        Amount
coffee          12
bagel          4.5
juice            6
TOTAL         22.5

index,name,value
0,coffee,12
1,bagel,4.5
2,juice,6

render is the template method: the loop and the order of the steps are fixed. header and row must be implemented, while footer and showTotal have defaults that subclasses may override. If subclasses shouldn't change the template itself, annotate render with @nonVirtual from package:meta, which makes the analyzer warn about overrides. See Inheritance and Overriding.

When there are only one or two steps, passing functions to a constructor is often simpler than subclassing.

Chain of responsibility

A chain of responsibility passes a request along a list of handlers until one of them handles it. Here an expense goes up the management chain:

class Expense {
  final String what;
  final double amount;
  Expense(this.what, this.amount);
}

// Each handler either decides or passes the request to the next one.
abstract class Approver {
  Approver? _next;

  Approver then(Approver next) {
    _next = next;
    return next; // allows a.then(b).then(c)
  }

  String handle(Expense e) {
    if (canApprove(e)) return '$name approved ${e.what} (\$${e.amount})';
    final next = _next;
    return next == null
        ? 'nobody can approve ${e.what} (\$${e.amount})'
        : next.handle(e);
  }

  String get name;
  bool canApprove(Expense e);
}

class TeamLead extends Approver {
  @override
  String get name => 'team lead';
  @override
  bool canApprove(Expense e) => e.amount <= 100;
}

class Manager extends Approver {
  @override
  String get name => 'manager';
  @override
  bool canApprove(Expense e) => e.amount <= 1000;
}

class Director extends Approver {
  @override
  String get name => 'director';
  @override
  bool canApprove(Expense e) => e.amount <= 10000 && e.what != 'yacht';
}

void main() {
  final chain = TeamLead();
  chain.then(Manager()).then(Director());

  for (final e in [
    Expense('pizza', 45),
    Expense('monitor', 450),
    Expense('server', 7500),
    Expense('yacht', 9000),
  ]) {
    print(chain.handle(e));
  }
}

Output:

team lead approved pizza ($45.0)
manager approved monitor ($450.0)
director approved server ($7500.0)
nobody can approve yacht ($9000.0)

The client only talks to the first handler. Adding a new level means inserting another link, without changing the existing handlers.

The functional version of this pattern is middleware: each handler receives the next handler and decides whether, and how, to call it. Composing the list is a one-line fold:

typedef Handler = String Function(String path);
typedef Middleware = Handler Function(Handler next);

Middleware logging(List<String> log) => (next) => (path) {
      log.add('-> $path');
      final result = next(path);
      log.add('<- $result');
      return result;
    };

Middleware auth(Set<String> public) => (next) => (path) =>
    !path.startsWith('/admin') || public.contains(path)
        ? next(path)
        : '403 Forbidden';

Handler pipeline(List<Middleware> middlewares, Handler handler) =>
    middlewares.reversed.fold(handler, (h, m) => m(h));

void main() {
  final log = <String>[];
  final app = pipeline(
    [logging(log), auth({'/admin/login'})],
    (path) => '200 OK $path',
  );
  print(app('/home'));
  print(app('/admin/users'));
  print(app('/admin/login'));
  print(log);
}

Output:

200 OK /home
403 Forbidden
200 OK /admin/login
[-> /home, <- 200 OK /home, -> /admin/users, <- 403 Forbidden, -> /admin/login, <- 200 OK /admin/login]

The auth middleware stopped /admin/users without calling the final handler, while logging wrapped every request. The shelf package builds HTTP servers exactly this way; see HTTP middleware.

Iterator

The iterator pattern gives sequential access to a collection without exposing how it's stored. It's built into Dart: anything that extends Iterable works with for-in and gets dozens of methods (map, where, take, join, toList...) for free. You can implement Iterator by hand, but a sync* generator is usually much shorter:

// A custom Iterable gets map, where, take, toList... for free.
class Fibonacci extends Iterable<int> {
  @override
  Iterator<int> get iterator => _FibIterator();
}

class _FibIterator implements Iterator<int> {
  int _a = 0, _b = 1;
  @override
  int current = 0;

  @override
  bool moveNext() {
    current = _a;
    final next = _a + _b;
    _a = _b;
    _b = next;
    return true; // infinite sequence
  }
}

// The same thing with a sync* generator.
Iterable<int> fibonacci() sync* {
  var (a, b) = (0, 1);
  while (true) {
    yield a;
    (a, b) = (b, a + b);
  }
}

class TreeNode<T> {
  final T value;
  final List<TreeNode<T>> children;
  TreeNode(this.value, [this.children = const []]);

  // Depth-first traversal; yield* delegates to a nested iterable.
  Iterable<T> get depthFirst sync* {
    yield value;
    for (final c in children) {
      yield* c.depthFirst;
    }
  }
}

void main() {
  print(Fibonacci().take(10).toList());
  print(fibonacci().where((n) => n.isOdd).skip(3).take(4).toList());

  final tree = TreeNode('root', [
    TreeNode('a', [TreeNode('a1'), TreeNode('a2')]),
    TreeNode('b'),
  ]);
  print(tree.depthFirst.join(' '));
  for (final name in tree.depthFirst.where((n) => n.length == 2)) {
    print('leaf: $name');
  }
}

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[5, 13, 21, 55]
root a a1 a2 b
leaf: a1
leaf: a2

Iterables are lazy, so even an infinite Fibonacci sequence is fine as long as you take a finite part of it. yield* delegates to a nested iterable, which keeps recursive traversals like depthFirst short. The asynchronous counterpart is async*, which produces a Stream. See Sync and async generators.

Summary

Pattern Idiomatic Dart
Factory factory constructor, possibly with a cache
Builder named parameters with defaults and copyWith; a builder class with cascades for step-by-step construction
Strategy a function type, with tear-offs or closures
Adapter a class that implements your interface; extensions for API sugar
Proxy a class with the same interface that wraps the real object
Observer StreamController.broadcast(), or a list of callbacks
Command objects with execute/undo, or plain functions when undo isn't needed
State sealed classes for states and events, switch on (state, event)
Visitor exhaustive switch over a sealed hierarchy
Template method abstract class with abstract steps and hook methods
Chain of responsibility linked handlers, or middleware functions composed with fold
Iterator extend Iterable, or write a sync* generator

Don't use patterns for their own sake. Reach for the simplest Dart feature that solves the problem, and introduce a pattern when the code actually needs the flexibility it provides.

Feedback about page:

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



Table Of Contents