On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Problem
  4. 2. A Builder Class
  5. 3. A Builder You Already Have: StringBuffer
  6. 4. Builders and Cascades
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 051: Builder Class

DayExtra Topics
Lecture051 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

Pizza('large', true, false, true): what do true, false, true mean? When an object has many options, a constructor call turns into a puzzle. A builder class lets you set the options one readable step at a time, then build the finished object.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 029 (cascade notation), 030–033 (classes and constructors) and 046 (private fields).


Learning Objectives

  • Recognise when a constructor has too many options
  • Write a builder class whose methods return this
  • Chain builder methods and finish with build()
  • Use Dart's built-in StringBuffer builder
  • Compare a builder with cascades (..)

1. The Problem

dart
class Pizza {
  final String size;
  final bool cheese;
  final bool olives;
  final bool mushrooms;

  Pizza(this.size, this.cheese, this.olives, this.mushrooms);

  @override
  String toString() => '$size pizza (cheese: $cheese, olives: $olives, mushrooms: $mushrooms)';
}

var hard = Pizza('large', true, false, true);   // which one is olives again?

2. A Builder Class

The builder holds the options with sensible defaults. Each method sets one option and returns the builder itself (return this;), so the calls can be chained:

dart
class PizzaBuilder {
  String _size = 'medium';
  bool _cheese = false;
  bool _olives = false;
  bool _mushrooms = false;

  PizzaBuilder size(String size) {
    _size = size;
    return this;
  }

  PizzaBuilder addCheese() {
    _cheese = true;
    return this;
  }

  PizzaBuilder addOlives() {
    _olives = true;
    return this;
  }

  PizzaBuilder addMushrooms() {
    _mushrooms = true;
    return this;
  }

  Pizza build() => Pizza(_size, _cheese, _olives, _mushrooms);
}

void main() {
  var pizza = PizzaBuilder().size('large').addCheese().addMushrooms().build();
  print(pizza);

  var plain = PizzaBuilder().build();
  print(plain);
}

Output

code
large pizza (cheese: true, olives: false, mushrooms: true)
medium pizza (cheese: false, olives: false, mushrooms: false)

The chain reads like an order: a large pizza, add cheese, add mushrooms, build it. Options you skip keep their defaults.

3. A Builder You Already Have: StringBuffer

Joining many strings with + creates a new string every time. Dart's StringBuffer collects the pieces and builds the final string once:

dart
var buffer = StringBuffer();
buffer.write('Hello');
buffer.write(', ');
buffer.write('Dart');
print(buffer.toString());   // Hello, Dart

4. Builders and Cascades

StringBuffer.write doesn't return the buffer, so it can't be chained with .. Cascades (.., Lecture 029) call several methods on the same object anyway:

dart
var sb = StringBuffer()
  ..write('A')
  ..write('B')
  ..writeln('C')   // writeln adds a new line
  ..write('D');
print(sb);

Output

code
ABC
D
Builder methods with return thisCascades ..
Works on any class?only classes written for ityes
Can check everything before building?yes, in build()no

Code Examples

Example 1: Building an Email

dart
class Email {
  final String to;
  final String subject;
  final String body;
  final List<String> cc;

  Email(this.to, this.subject, this.body, this.cc);

  void send() {
    print('To: $to');
    if (cc.isNotEmpty) print('Cc: ${cc.join(', ')}');
    print('Subject: $subject');
    print('');
    print(body);
  }
}

class EmailBuilder {
  String? _to;
  String _subject = '(no subject)';
  final _body = StringBuffer();
  final List<String> _cc = [];

  EmailBuilder to(String address) {
    _to = address;
    return this;
  }

  EmailBuilder subject(String text) {
    _subject = text;
    return this;
  }

  EmailBuilder line(String text) {
    _body.writeln(text);
    return this;
  }

  EmailBuilder cc(String address) {
    _cc.add(address);
    return this;
  }

  Email build() {
    if (_to == null) {
      throw StateError('An email needs a "to" address');
    }
    return Email(_to!, _subject, _body.toString().trimRight(), _cc);
  }
}

void main() {
  var email = EmailBuilder()
      .to('team@codingmentor.app')
      .cc('sara@mail.com')
      .subject('Class moved to Friday')
      .line('Hi everyone,')
      .line('Tomorrow\'s class is moved to Friday at 5 pm.')
      .line('See you there!')
      .build();

  email.send();
}

Output

code
To: team@codingmentor.app
Cc: sara@mail.com
Subject: Class moved to Friday

Hi everyone,
Tomorrow's class is moved to Friday at 5 pm.
See you there!

build() checks the one required option (to) before creating the email. That check is something a builder can do and a cascade can't.


Common Beginner Mistakes

1. Forgetting return this

dart
class Builder {
  int _n = 0;
  void add() {
    _n++;
  }
}

Builder().add().add();
code
Error: This expression has type 'void' and can't be used.

A method that returns void ends the chain. Return the builder: Builder add() { _n++; return this; }

2. Forgetting build(): PizzaBuilder().addCheese() is still a builder, not a pizza.

3. Building simple objects with a builder: for two or three fields, named parameters (Pizza(size: 'large', cheese: true)) are clearer. Use a builder when there are many options or steps.


Practice Questions

  1. Why does each builder method end with return this;?
  2. What is PizzaBuilder().build() if no options were set?
  3. Which Dart class builds strings piece by piece?
  4. What can build() do that a cascade can't?
  5. Add a method addOlives() to a builder that sets _olives = true.

Practice Answers

  1. So the next method can be called on the same builder (chaining).
  2. A medium pizza with no toppings: the defaults.
  3. StringBuffer
  4. Check that the options are valid (for example, a required field is set) before creating the object.
dart
PizzaBuilder addOlives() {
  _olives = true;
  return this;
}

Key Takeaways

  • A builder sets an object's options step by step, then build() creates it.
  • Builder methods return this so they can be chained.
  • Defaults live in the builder; skipped options keep them.
  • StringBuffer is Dart's built-in builder for strings.
  • Prefer named parameters for simple objects; use builders for many options.