Here is a comparison of several different ways to create a singleton in Dart.
1. Factory Designer
class SingletonOne { SingletonOne._privateConstructor(); static final SingletonOne _instance = SingletonOne._privateConstructor(); factory SingletonOne(){ return _instance; } }
2. Static field with getter
class SingletonTwo { SingletonTwo._privateConstructor(); static final SingletonTwo _instance = SingletonTwo._privateConstructor(); static SingletonTwo get instance { return _instance;} }
3. Static field
class SingletonThree { SingletonThree._privateConstructor(); static final SingletonThree instance = SingletonThree._privateConstructor(); }
How to create an instance
The above singletones are created as follows:
SingletonOne one = SingletonOne(); SingletonTwo two = SingletonTwo.instance; SingletonThree three = SingletonThree.instance;
Remarks:
I initially asked this as a question , but found that all the methods listed above are valid, and the choice largely depends on personal preferences.
Suragch Mar 26 '19 at 0:25 2019-03-26 00:25
source share