{

How to Create and build a Singleton Class Dart or Flutter example| Dart By 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 constants 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 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.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example

Dart| Flutter How to: Create a private variable with example