How to implement Singleton pattern in Dart using factory constructors? How to implement Singleton pattern in Dart using factory constructors? dart dart

How to implement Singleton pattern in Dart using factory constructors?


There is no need to use the factory constructor.The factory constructor was convenient when new was not yet optional because then it new MyClass() worked for classes where the constructor returned a new instance every time or where the class returned a cached instance. It was not the callers responsibility to know how and when the object was actually created.

You can change

factory DbHelper(){ return _db;} 

to

DbHelper get singleton { return _db;}   

and acquire the instance using

var mySingletonReference = DbHelper.singleton;

instead of

var mySingletonReference = DbHelper();

It's just a matter of preference.