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.
Singleton is a basic design pattern. It is used to create a single object instance for a class in Dart.
Singleton features
There are multiple ways we can create a singleton instance always for a given class
_
)==
and identical
methodThe 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
this post shows how to create a singleton design pattern class example in dart.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts