How do you build a Singleton in Dart?

CodeWithFlutter
2 Min Read

A singleton is a design pattern that restricts a class to a single instance and provides a global point of access to that instance. In Dart, you can implement a singleton by following these steps:

  1. Define a private constructor: To prevent other objects from creating instances of the class, you should define a private constructor. This makes it impossible for other objects to instantiate the class using the new keyword.
  2. Declare a private static instance variable: You should declare a private static instance variable to store the single instance of the class. This variable is often called _instance.
  3. Implement a factory constructor: To provide a way for clients to access the single instance of the class, you should implement a factory constructor. This constructor returns the existing instance of the class if it has already been created, or creates a new instance if it has not.

Here is an example of how you can implement a singleton in Dart:

class Singleton {
  static final Singleton _instance = Singleton._internal();

  factory Singleton() {
    return _instance;
  }

  Singleton._internal();

  void doSomething() {
    print('Singleton doing something.');
  }
}

In this example, the Singleton class has a private constructor that is called by the factory constructor to create the single instance of the class. Clients can access the single instance of the class by calling the factory constructor without the new keyword.

Share this Article
Leave a comment