On this page11 sections
Lecture 034: The Singleton Pattern
| Day | 12: Singleton, Getters & Static |
| Lecture | 034 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
Some things should exist only once in an app: the settings, the shopping cart, the logger. If every screen created its own cart, items added on one screen would vanish on the next. A singleton is a class that only ever has one object, shared by everyone.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 030–033 (classes and constructors). This lecture previews static (Lecture 036) and
private names starting with _ (Lecture 046).
Learning Objectives
- Explain what a singleton is and when to use one
- Build one with a private constructor, a
staticinstance and afactoryconstructor - Check that two variables hold the same object with
identical - Recognise the
instancegetter style
1. The Problem
A normal class creates a new object on every call:
class Settings {
Settings();
}
print(identical(Settings(), Settings())); // falseidentical(a, b) is true only when a and b are the same object. Two separate settings
objects means a change in one is invisible to the other.
2. Building a Singleton
class AppSettings {
static final AppSettings _instance = AppSettings._internal();
String theme = 'light';
String language = 'English';
AppSettings._internal() {
print('AppSettings created');
}
factory AppSettings() => _instance;
}Three pieces work together:
AppSettings._internal()is a named constructor whose name starts with_, which makes it private to this file. Other files can't call it, so they can't make new objects.static final _instanceis the one and only object, created once.staticmeans it belongs to the class itself, not to any object (Lecture 036).factory AppSettings()is the constructor everyone calls. Afactoryconstructor is allowed to return an existing object instead of building a new one, and here it always returns_instance.
var a = AppSettings();
var b = AppSettings();
print(identical(a, b)); // true
a.theme = 'dark';
print(b.theme); // darkOutput
AppSettings created
true
darkAppSettings created prints only once, however many times AppSettings() is called.
3. Another Style: an instance Getter
Some code (including many packages) exposes the singleton through a static getter instead:
class Logger {
static Logger? _instance;
final List<String> messages = [];
Logger._();
static Logger get instance => _instance ??= Logger._();
void log(String m) => messages.add(m);
}
Logger.instance.log('App started');
Logger.instance.log('User logged in');
print(Logger.instance.messages); // [App started, User logged in]_instance ??= Logger._() creates the object the first time it's needed, then reuses it
(??=, Lecture 018).
4. When to Use a Singleton
| Good fit | Not a good fit |
|---|---|
| app-wide settings, a cart, a logger, a database connection | ordinary data with many copies (users, products, orders) |
Use singletons sparingly. Too many of them make code hard to test.
Code Examples
Example 1: One Cart for the Whole App
class Cart {
static final Cart _instance = Cart._internal();
factory Cart() => _instance;
Cart._internal();
final List<String> _items = [];
void add(String item) {
_items.add(item);
print('Added $item (${_items.length} in cart)');
}
List<String> get items => List.unmodifiable(_items);
}
void productPage() {
Cart().add('Shoes');
}
void searchPage() {
Cart().add('Socks');
}
void checkoutPage() {
print('Checking out: ${Cart().items}');
}
void main() {
productPage();
searchPage();
checkoutPage();
}Output
Added Shoes (1 in cart)
Added Socks (2 in cart)
Checking out: [Shoes, Socks]Each "page" calls Cart() separately, but they all get the same cart, so checkout sees both
items. (get items is a getter, the topic of Lecture 035.)
Common Beginner Mistakes
1. Calling the private constructor from another file
main.dart (with the class in app_settings.dart)
import 'app_settings.dart';
void main() {
var s = AppSettings._internal();
}Error: Member not found: 'AppSettings._internal'.That's the point: only AppSettings() is available outside the file. (Inside the same file _
hides nothing, which is why singletons usually live in their own file.)
2. Forgetting factory: a normal constructor always builds a new object. Only a factory
constructor can hand back the existing _instance.
3. Making everything a singleton: data that has many copies (students, products) should be normal classes.
Practice Questions
- What does "singleton" mean?
- What does
identical(a, b)check? - Why is the constructor named
_internal(with an underscore)? - What is special about a
factoryconstructor? - Give one example of something that should be a singleton, and one that shouldn't.
Practice Answers
- A class that only ever has one object, shared across the app.
- Whether
aandbare the very same object. - The
_makes it private to its file, so no other code can create extra objects. - It can return an existing object instead of always creating a new one.
- Should: app settings or a cart. Shouldn't: a
Product, since there are many products.
Key Takeaways
- A singleton has exactly one object.
- Pattern: private constructor +
static final _instance+factoryconstructor returning it. identical(a, b)confirms two variables share one object.- A
staticinstancegetter with??=is a common alternative. - Use singletons only for truly app-wide things.