Singleton Pattern in Flutter

Syed Abdul Basit
4 min readAug 26, 2024

The Singleton pattern, one of the well-known “Gang of Four” design patterns, is a crucial concept for any Flutter developer. This creational design pattern ensures that a class has only one instance while providing global access to that instance.

What Makes a Singleton?

At its core, the Singleton pattern is all about controlling the creation of a single instance of a class. The key elements are:

  1. Single Instance: Only one instance of the class exists.
  2. Global Access: Easy access to this instance globally.
  3. Controlled Instantiation: The constructor is made private to prevent direct instantiation.
  4. Thread Safety: Any critical section of code must be accessed serially.

Implementing Singleton in Dart

Let’s dive into the implementation of the singleton pattern in DART using the classical approach.

class Singleton {
static Singleton? _instance;

// Private constructor
Singleton._internal() {
print('Creating an instance of the Singleton');
}

// Lazy instantiation
static Singleton get instance {
_instance ??= Singleton._internal();
return _instance!;
}
}

void main(){
Singleton.instance;
Singleton.instance;
}

--

--

Responses (2)