How do build a Singleton in Dart?

When you need to ensure only a single instance of a class is created, and you want to provide a global point of access to it, the Singleton design pattern can be of great help. Examples of typical singletons include an app-wide debug logger or the data model for an app’s configuration settings. If multiple parts of an app need access to such an object, each area could create its own instance or have one passed to it, but the Singleton pattern offers a cleaner, more memory efficient way.

This is useful when you want to have a single instance of a class throughout your application, such as a database manager, logger, or configuration manager.

Here’s how you can implement a Singleton in Dart:

class Singleton {
  // Private constructor
  Singleton._privateConstructor();

  // Static instance variable
  static final Singleton _instance = Singleton._privateConstructor();

  // Factory constructor to return the instance
  factory Singleton() {
    return _instance;
  }

  // Example method
  void printMessage() {
    print("Hello, I'm a Singleton!");
  }
}

void main() {
  // Accessing the Singleton instance
  Singleton singleton1 = Singleton();
  Singleton singleton2 = Singleton();

  // Both instances point to the same object
  print(identical(singleton1, singleton2)); // Output: true

  // Using Singleton methods
  singleton1.printMessage(); // Output: Hello, I'm a Singleton!
}

Output:

  • We define a class named Singleton.
  • We declare a private constructor Singleton._privateConstructor() to prevent direct instantiation of the class from outside.
  • We declare a static private variable _instance of type Singleton within the class. This variable holds the single instance of the class.
  • We define a factory constructor named Singleton() to return the instance of the class. Since the constructor is a factory constructor, it can return an existing instance or create a new one if needed.
  • We use the identical() function to check whether singleton1 and singleton2 reference the same object. Since Singleton() returns the same instance (_instance) every time it’s called, both variables point to the same object.
  • We call the printMessage() method on singleton1 to demonstrate accessing and using methods of the Singleton instance.

Using the Singleton pattern ensures that only one instance of the class exists throughout the application, preventing multiple instances from being created accidentally. This can be beneficial for managing shared resources or maintaining a consistent state across the application.

How do build a Singleton in Dart

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More