How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

Singleton is a fundamental design pattern used to ensure only a single instance of a class exists in Dart.

Singleton Features

  • Lazily creates an instance of a class.
  • Only one instance is ever created.
  • Objects can only be created using a static method.
  • Employs a private constructor.

Dart Singleton Example

There are multiple methods to create a singleton instance consistently for a given class.

  • Define a Singleton class.
  • Establish a final static compile-time constant for an instance of the Singleton class.
  • Implement a named private constructor prefixed with an underscore (_).
  • Construct an empty constructor and apply the factory keyword to it. A factory constructor always returns an instance of the current class, ensuring a Singleton class instance.
  • Instantiate two instances of the Singleton class within the main method and compare them using the == operator and the identical method.

The following program demonstrates eager loading for a singleton instance:

main() {
  var singleton1 = Singleton();
  var singleton2 = Singleton();
  print(identical(singleton1, singleton2));
  print(singleton1 == singleton2);
}
class Singleton {
  static final Singleton _singleton = Singleton._SingletonConstructor();

  factory Singleton() {
    return _singleton;
  }

  Singleton._SingletonConstructor();
}

Output:

true
true

Let’s explore the singleton Lazy loading example.

In this case, the factory constructor checks if an instance is null. If it is null, it creates an instance of the class; otherwise, it returns the existing instance.

main() {
  var singleton1 = Singleton();
  var singleton2 = Singleton();
  print(identical(singleton1, singleton2));
  print(singleton1 == singleton2);
}

class Singleton {
  static Singleton _singleton = Singleton._SingletonConstructor();

  factory Singleton() => _singleton ??= Singleton._SingletonConstructor();

  Singleton._SingletonConstructor();
}

Output:

true
true

Conclusion

This post illustrates how to implement a singleton design pattern class example in Dart, covering both Lazy Loading and Eager Loading scenarios.