The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?
-
2I have seen several answers below which describe several ways for making a class singleton. So I am thinking about why we don't do like this class_name object; if(object == null ) return object= new class_name; else return objectAvnish Nishad– Avnish Nishad2020-05-31 19:31:42 +00:00Commented May 31, 2020 at 19:31
-
2because static instance is lazy initialized by default in DartMohammad Alotol– Mohammad Alotol2022-03-19 18:57:12 +00:00Commented Mar 19, 2022 at 18:57
Add a comment
|
32 Answers
For creating singleton object you can use get_it package.
To create singleton:
GetIt.I.registerSingleton(YourClass());
To get singleton object:
GetIt.I<YourClass>()
Comments
You can just use the Constant constructors.
class Singleton {
const Singleton(); //Constant constructor
void hello() { print('Hello world'); }
}
Example:
Singleton s = const Singleton();
s.hello(); //Hello world
According with documentation:
Constant constructors
If your class produces objects that never change, you can make these objects compile-time constants. To do this, define a const constructor and make sure that all instance variables are final.
3 Comments
CloudBalancing
The issue with const. is that your singleton will not be able to have state that is changed
Salvatore Gerace
@CloudBalancing You can just use static variables for the state.
scrimau
This is not a singleton. You can instantiate many different instances of a class with a const constructor. This is supposed to be prevented by a singleton.