Singletons

suggest change

A singleton is a class that has exactly one instance for the whole program, plus a well-known way to get to it. Typical examples are application settings, a metrics registry, a connection pool or a cache.

Dart makes singletons unusually easy, because of two language features:

This article covers:

The classic singleton: a factory constructor

The most common Dart singleton has three parts: a private named constructor, a private static field holding the one instance, and a public factory constructor that returns it:

class AppSettings {
  AppSettings._internal() {
    print('AppSettings created');
  }

  static final AppSettings _instance = AppSettings._internal();

  factory AppSettings() => _instance;

  String theme = 'light';
  int fontSize = 14;
}

void main() {
  print('main started');
  final a = AppSettings();
  final b = AppSettings();

  a.theme = 'dark';
  print(b.theme);
  print(identical(a, b));
  print(a == b);
}

Output:

main started
AppSettings created
dark
true
true

How it works:

Notice that AppSettings created is printed after main started, not when the program loads. The _instance field is initialized the first time it's read.

The advantage of this style is that callers write AppSettings() and don't need to know it's a singleton. The disadvantage is the same thing: AppSettings() looks like it creates a new object, which can surprise a reader.

The static final instance style

Many Dart libraries skip the factory and expose the instance directly. This is explicit at the call site and needs less code:

class Metrics {
  Metrics._();

  static final instance = Metrics._();

  final _counters = <String, int>{};

  void increment(String name) =>
      _counters.update(name, (v) => v + 1, ifAbsent: () => 1);

  int operator [](String name) => _counters[name] ?? 0;
}

void handleRequest() => Metrics.instance.increment('requests');

void main() {
  handleRequest();
  handleRequest();
  Metrics.instance.increment('errors');

  print(Metrics.instance['requests']);
  print(Metrics.instance['errors']);
  print(Metrics.instance['missing']);
  // Metrics(); // compile error: no unnamed constructor
}

Output:

2
1
0

Because the field is final, nobody can replace the instance. Flutter itself uses this pattern, for example WidgetsBinding.instance and PaintingBinding.instance.

Some code bases use a getter instead (static Metrics get instance => _instance;). That's useful when you want to add logic later, such as an "initialized?" check, without changing callers. See Static members for more on static fields and methods.

Lazy initialization is built in

In Java or C# a lazy, thread-safe singleton needs care. In Dart, every static field and top-level variable with an initializer is lazy: the initializer runs on first access, exactly once. A Dart isolate runs one piece of code at a time, so there are no races between threads.

class Heavy {
  Heavy() {
    print('  Heavy constructor runs');
  }
  static final shared = Heavy();
}

final topLevelHeavy = () {
  print('  top-level initializer runs');
  return 42;
}();

void main() {
  print('start');
  print('before first access to Heavy.shared');
  final h1 = Heavy.shared;
  print('after first access');
  final h2 = Heavy.shared;
  print(identical(h1, h2));

  print('before first access to topLevelHeavy');
  print(topLevelHeavy);
  print(topLevelHeavy);
}

Output:

start
before first access to Heavy.shared
  Heavy constructor runs
after first access
true
before first access to topLevelHeavy
  top-level initializer runs
42
42

This means a top-level final variable is often all you need:

// metrics.dart
final metrics = Metrics();

It's lazy, created once, and can't be reassigned. The only thing it doesn't do is stop someone from calling Metrics() and making a second object. Whether that matters depends on the class: for a stateless helper it's harmless, for something that owns a file handle it's a bug, and a private constructor is the better choice.

When the initializer throws

If the initializer of a static or top-level variable throws, the variable stays uninitialized and the exception propagates to the code that read it. The next read runs the initializer again:

var attempts = 0;

class Connection {
  Connection._() {
    attempts++;
    print('connecting, attempt $attempts');
    if (attempts < 2) throw StateError('server not ready');
  }

  static final instance = Connection._();
}

void main() {
  try {
    Connection.instance;
  } catch (e) {
    print('failed: $e');
  }
  final c = Connection.instance;
  print('got ${c.runtimeType}');
  print(identical(c, Connection.instance));
}

Output:

connecting, attempt 1
failed: Bad state: server not ready
connecting, attempt 2
got Connection
true

That's convenient for transient failures, but it also means an expensive, failing initializer is retried on every access. If that's a problem, catch the error inside the initializer and store a fallback.

Singletons that need configuration

A static field initializer can't take arguments. If the instance needs values that are only known at startup, such as command-line flags or an environment, make initialization an explicit step:

class Config {
  final String apiUrl;
  final bool verbose;

  Config._(this.apiUrl, this.verbose);

  static Config? _instance;

  static Config get instance {
    final config = _instance;
    if (config == null) {
      throw StateError('Config.init() must be called first');
    }
    return config;
  }

  static void init({required String apiUrl, bool verbose = false}) {
    if (_instance != null) {
      throw StateError('Config.init() called twice');
    }
    _instance = Config._(apiUrl, verbose);
  }
}

void main() {
  try {
    print(Config.instance.apiUrl);
  } on StateError catch (e) {
    print(e.message);
  }

  Config.init(apiUrl: 'https://api.example.com', verbose: true);
  print(Config.instance.apiUrl);
  print(Config.instance.verbose);

  try {
    Config.init(apiUrl: 'https://other.example.com');
  } on StateError catch (e) {
    print(e.message);
  }
}

Output:

Config.init() must be called first
https://api.example.com
true
Config.init() called twice

Copying _instance into a local variable lets null safety promote it to Config, so there's no need for !.

You could write static late final Config instance; instead. Reading it before assignment throws a LateInitializationError, and assigning it twice throws as well. That's shorter, but the error messages are generic, so the explicit version above is friendlier when other developers forget to call init().

Async initialization

Opening a database or reading a config file is asynchronous, and constructors can't be async. The tempting approach is a nullable field checked inside an async getter:

class Database {
  Database._();
  static Database? _instance;

  static Future<Database> get instance async {
    if (_instance == null) {
      print('opening database...');
      await Future.delayed(const Duration(milliseconds: 100));
      _instance = Database._();
    }
    return _instance!;
  }
}

Future<void> main() async {
  final dbs = await Future.wait([Database.instance, Database.instance]);
  print(identical(dbs[0], dbs[1]));
}

Output:

opening database...
opening database...
false

This is broken. Dart has no threads, but it does have interleaving at every await. The second caller checks _instance while the first is still waiting, sees null, and opens a second database.

The fix is to cache the Future, not the result. Every caller gets the same future, and the opening code runs once:

class Database {
  final String path;
  Database._(this.path);

  static Future<Database>? _opening;

  static Future<Database> get instance => _opening ??= _open();

  static Future<Database> _open() async {
    print('opening database...');
    await Future.delayed(const Duration(milliseconds: 100));
    print('database open');
    return Database._('app.db');
  }

  Future<List<String>> query(String sql) async => ['row for: $sql'];
}

Future<void> main() async {
  // three callers ask at the same time, before the first open finished
  final results = await Future.wait([
    Database.instance,
    Database.instance,
    Database.instance,
  ]);
  print(identical(results[0], results[1]) && identical(results[1], results[2]));

  final db = await Database.instance;
  print(await db.query('SELECT 1'));
}

Output:

opening database...
database open
true
[row for: SELECT 1]

_opening ??= _open() assigns only when _opening is null, and _open() returns its future synchronously at the first await, so the field is set before any other caller can run.

One catch remains: if opening fails, the failed future is cached forever. To allow a retry, clear the field on error:

var attempt = 0;

class Database {
  Database._();

  static Future<Database>? _opening;

  static Future<Database> get instance {
    return _opening ??= _open().catchError((Object e) {
      _opening = null; // forget the failure so the next call retries
      throw e;
    });
  }

  static Future<Database> _open() async {
    attempt++;
    print('open attempt $attempt');
    await Future.delayed(const Duration(milliseconds: 10));
    if (attempt == 1) throw StateError('connection refused');
    return Database._();
  }
}

Future<void> main() async {
  try {
    await Database.instance;
  } on StateError catch (e) {
    print('error: ${e.message}');
  }
  final a = await Database.instance;
  final b = await Database.instance;
  print(identical(a, b));
}

Output:

open attempt 1
error: connection refused
open attempt 2
true

See Async and Await and Returning a Future using a Completer for more on futures.

const objects are canonicalized

For immutable values you may not need a singleton class at all. Dart canonicalizes constant objects: every const expression with the same class and the same field values evaluates to the same instance.

class Color {
  final int r, g, b;
  const Color(this.r, this.g, this.b);

  static const black = Color(0, 0, 0);
}

void main() {
  const a = Color(0, 0, 0);
  const b = Color(0, 0, 0);
  final c = Color(0, 0, 0); // not const: a new object

  print(identical(a, b));
  print(identical(a, Color.black));
  print(identical(a, c));
}

Output:

true
true
false

Constant objects are created at compile time and are deeply immutable, which makes them a good fit for things like default options, empty states and stateless strategy objects. They can't hold mutable state, so they don't replace a singleton that tracks something. See Constants and Immutability.

A single-value enum

An enhanced enum with exactly one value is a compact, guaranteed singleton. Enums can't be instantiated or subclassed, and they can have methods:

enum Clock {
  instance;

  DateTime now() => DateTime.utc(2026, 10, 17, 12);

  String timestamp() => now().toIso8601String();
}

void main() {
  print(Clock.instance.timestamp());
  print(identical(Clock.instance, Clock.values.single));
  // Clock(); // compile error: enums can't be instantiated
}

Output:

2026-10-17T12:00:00.000Z
true

The limit is that enum fields must be final and the enum's constructor must be const, so this works only for stateless or immutable singletons. Some readers also find it surprising to see an enum used this way, so the static final instance style is more common in Dart code.

One instance per isolate

"One instance per program" is really "one instance per isolate". Isolates don't share memory, so each isolate has its own copy of every static field, initialized separately:

import 'dart:isolate';

class Counter {
  Counter._();
  static final instance = Counter._();
  int value = 0;
}

Future<void> main() async {
  Counter.instance.value = 10;

  final seenByIsolate = await Isolate.run(() {
    Counter.instance.value += 1;
    return Counter.instance.value;
  });

  print('in isolate: $seenByIsolate');
  print('in main: ${Counter.instance.value}');
}

Output:

in isolate: 1
in main: 10

The worker isolate started with a fresh Counter whose value was 0. Changes in one isolate are never seen in another. If several isolates need shared state, keep it in one isolate and send messages to it. See Isolates.

Keyed instances (multiton)

Sometimes you want one instance per key: one logger per name, one connection pool per host. A factory constructor with a cache map does it:

class Logger {
  final String name;
  Logger._(this.name);

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

  factory Logger(String name) =>
      _cache.putIfAbsent(name, () => Logger._(name));

  void info(String msg) => print('[$name] $msg');
}

void main() {
  final a = Logger('http');
  final b = Logger('db');
  final c = Logger('http');

  a.info('GET /');
  b.info('SELECT 1');
  print(identical(a, c));
  print(identical(a, b));
}

Output:

[http] GET /
[db] SELECT 1
true
false

This is how Logger in the official logging package works: Logger('http') anywhere in the program returns the same object. See Logging.

The cache keeps every instance alive forever. That's fine for a bounded set of keys, but don't use it with user-supplied keys, or it becomes a memory leak. See Caching for caches with eviction.

Preventing subclasses and fake implementations

A class whose only generative constructor is private can't be extended from another library, because a subclass constructor must call a superclass constructor. It can still be implemented, though, since implements doesn't call constructors.

If you want to forbid both, declare it a final class. Given this library:

// registry.dart
final class Registry {
  Registry._();
  static final instance = Registry._();
  final items = <String>[];
}

another file that tries to extend or implement it gets compile errors:

import 'registry.dart';

class MyRegistry extends Registry {}

class FakeRegistry implements Registry {
  @override
  List<String> get items => [];
}

dart analyze reports (locations and hints trimmed):

error - The superclass 'Registry' doesn't have a zero argument constructor. - no_default_super_constructor
error - The class 'Registry' can't be extended outside of its library because it's a final class. - invalid_use_of_type_outside_library
error - The class 'Registry' can't be implemented outside of its library because it's a final class. - invalid_use_of_type_outside_library

Think twice before using final here. Being able to implement a class with a fake is exactly what tests need, which leads to the main problem with singletons.

Singletons and testing

A singleton is global state. Code that calls Metrics.instance directly has a hidden dependency: you can't tell from its signature that it uses metrics, and tests can't easily swap in something else. State also leaks between tests, because the instance survives from one test to the next.

A common middle ground is to put the singleton behind an interface and allow tests to replace it:

abstract interface class Clock {
  DateTime now();
}

class SystemClock implements Clock {
  @override
  DateTime now() => DateTime.now();
}

class FixedClock implements Clock {
  final DateTime time;
  FixedClock(this.time);
  @override
  DateTime now() => time;
}

class Services {
  Services._();

  static Clock _clock = SystemClock();
  static Clock get clock => _clock;

  // only for tests
  static void overrideClock(Clock clock) => _clock = clock;
  static void reset() => _clock = SystemClock();
}

String greeting() {
  final hour = Services.clock.now().hour;
  return hour < 12 ? 'Good morning' : 'Good afternoon';
}

void main() {
  Services.overrideClock(FixedClock(DateTime(2026, 10, 17, 9)));
  print(greeting());

  Services.overrideClock(FixedClock(DateTime(2026, 10, 17, 15)));
  print(greeting());

  Services.reset();
  print(Services.clock.runtimeType);
}

Output:

Good morning
Good afternoon
SystemClock

In a real project, annotate test-only members with @visibleForTesting from package:meta so the analyzer warns when production code calls them, and call reset() in tearDown.

The cleaner fix is Dependency injection: create one instance in main and pass it to the classes that need it through their constructors. You still have a single instance, but it's a decision made in one place instead of being baked into the class. Service locators such as get_it sit in between: registerLazySingleton gives you a lazily created single instance that tests can re-register.

Choosing an approach

Need Use
a shared helper; a second instance is harmless top-level final variable
exactly one instance, explicit at call sites private constructor + static final instance
callers shouldn't know it's shared private constructor + factory returning a cached instance
configured at startup nullable static field + init() that throws if called twice
async setup (database, files) cache the Future: _opening ??= _open()
immutable value const constructor, or a single-value enum
one instance per key factory + Map.putIfAbsent
testable shared service create it once in main and inject it

Finally, keep singletons few. They're a good fit for things that really are one per process, such as configuration, a metrics registry or a connection pool. For everything else, passing objects explicitly keeps code easier to follow and to test.

Feedback about page:

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



Table Of Contents