How do you build a Singleton in Dart?

Seth Ladd picture Seth Ladd · Sep 29, 2012 · Viewed 94.3k times · Source

The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?

Answer

Seth Ladd picture Seth Ladd · Sep 29, 2012

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
}