On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Problem
  4. 2. Building a Singleton
  5. 3. Another Style: an instance Getter
  6. 4. When to Use a Singleton
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 034: The Singleton Pattern

Day12: Singleton, Getters & Static
Lecture034 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

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 static instance and a factory constructor
  • Check that two variables hold the same object with identical
  • Recognise the instance getter style

1. The Problem

A normal class creates a new object on every call:

dart
class Settings {
  Settings();
}

print(identical(Settings(), Settings()));   // false

identical(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

dart
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:

  1. 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.
  2. static final _instance is the one and only object, created once. static means it belongs to the class itself, not to any object (Lecture 036).
  3. factory AppSettings() is the constructor everyone calls. A factory constructor is allowed to return an existing object instead of building a new one, and here it always returns _instance.
dart
var a = AppSettings();
var b = AppSettings();
print(identical(a, b));   // true

a.theme = 'dark';
print(b.theme);           // dark

Output

code
AppSettings created
true
dark

AppSettings 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:

dart
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 fitNot a good fit
app-wide settings, a cart, a logger, a database connectionordinary 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

dart
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

code
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)

dart
import 'app_settings.dart';

void main() {
  var s = AppSettings._internal();
}
code
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

  1. What does "singleton" mean?
  2. What does identical(a, b) check?
  3. Why is the constructor named _internal (with an underscore)?
  4. What is special about a factory constructor?
  5. Give one example of something that should be a singleton, and one that shouldn't.

Practice Answers

  1. A class that only ever has one object, shared across the app.
  2. Whether a and b are the very same object.
  3. The _ makes it private to its file, so no other code can create extra objects.
  4. It can return an existing object instead of always creating a new one.
  5. 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 + factory constructor returning it.
  • identical(a, b) confirms two variables share one object.
  • A static instance getter with ??= is a common alternative.
  • Use singletons only for truly app-wide things.