On this page11 sections
Lecture 051: Builder Class
| Day | Extra Topics |
| Lecture | 051 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
Pizza('large', true, false, true): what dotrue, false, truemean? 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
StringBufferbuilder - Compare a builder with cascades (
..)
1. The Problem
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:
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
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:
var buffer = StringBuffer();
buffer.write('Hello');
buffer.write(', ');
buffer.write('Dart');
print(buffer.toString()); // Hello, Dart4. 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:
var sb = StringBuffer()
..write('A')
..write('B')
..writeln('C') // writeln adds a new line
..write('D');
print(sb);Output
ABC
DBuilder methods with return this | Cascades .. | |
|---|---|---|
| Works on any class? | only classes written for it | yes |
| Can check everything before building? | yes, in build() | no |
Code Examples
Example 1: Building an Email
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
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
class Builder {
int _n = 0;
void add() {
_n++;
}
}
Builder().add().add();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
- Why does each builder method end with
return this;? - What is
PizzaBuilder().build()if no options were set? - Which Dart class builds strings piece by piece?
- What can
build()do that a cascade can't? - Add a method
addOlives()to a builder that sets_olives = true.
Practice Answers
- So the next method can be called on the same builder (chaining).
- A medium pizza with no toppings: the defaults.
StringBuffer- Check that the options are valid (for example, a required field is set) before creating the object.
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 thisso they can be chained. - Defaults live in the builder; skipped options keep them.
StringBufferis Dart's built-in builder for strings.- Prefer named parameters for simple objects; use builders for many options.