Member-only story
Flutter | Dart — How do you build a Singleton in Dart
Thanks to Dart’s factory constructors, it’s easy to build a singleton
Sep 15, 2021
Thanks to Dart’s factory constructors, it’s easy to build a singleton:
class Singleton {
static final Singleton _singleton = Singleton._internal(); factory Singleton() {
return _singleton;
} Singleton._internal();
}
You can construct it like this
main() {
var s1 = Singleton();
var s2 = Singleton();
print(identical(s1, s2)); // true
print(s1 == s2); // true
}