{

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


 Singleton design pattern code  in Dart or Flutter example

Singleton is a basic design pattern. It is used to create a single object instance for a class in Dart.

Singleton features

  • Lazily created an instance of a class
  • Only one instance is created
  • Object can be created only with a static method
  • Private constructor

Dart singleton example

There are multiple ways we can create a singleton instance always for a given class

  • Create a Singleton class
  • Create a final static compile-time constant for an instance of the Singleton class
  • Create a named private constructor that starts with an underscore(_)
  • Create an empty constructor, and adds the factory keyword to it. Factory constructor always returns an instance of a current class. Return an instance of Singleton class
  • Create two instances of the Singleton class in the main method
  • both instances are compared using the == and identical method

The below program checks for 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 see the singleton Lazy loading example. In this example, the factory constructor, Checks for an instance is null, if it is null, create an instance of a class, else return an 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 shows how to create a singleton design pattern class example in dart.

  • Lazy Loading
  • Eager Loading
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.