548

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

2
  • 2
    I 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 object Commented May 31, 2020 at 19:31
  • 2
    because static instance is lazy initialized by default in Dart Commented Mar 19, 2022 at 18:57

32 Answers 32

1
2
0

For creating singleton object you can use get_it package.

To create singleton:

GetIt.I.registerSingleton(YourClass());

To get singleton object:

GetIt.I<YourClass>()
Sign up to request clarification or add additional context in comments.

Comments

-4

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

The issue with const. is that your singleton will not be able to have state that is changed
@CloudBalancing You can just use static variables for the state.
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.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.