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 object– Avnish NishadMay 31, 2020 at 19:31
-
1because static instance is lazy initialized by default in Dart– Mohammad AlotolMar 19, 2022 at 18:57
31 Answers
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
}
-
4Although what's the point of instantiating it twice? Shouldn't it be better if it threw an error when you instantiate it the second time?– westoqueMay 29, 2013 at 6:30
-
125I'm not instantiating it twice, just getting a reference to a Singleton object twice. You probably wouldn't do it twice in a row in real life :) I wouldn't want an exception thrown, I just want the same singleton instance every time I say "new Singleton()". I admit, it's a bit confusing...
new
doesn't mean "construct a new one" here, it just says "run the constructor". May 29, 2013 at 22:11 -
2What exactly does the factory keyword serve over here? It is purely annotating the implementation. Why is it required?– ΚαrτhικDec 3, 2013 at 14:29
-
17It's kind of confusing that you are using a constructor to get the instance. The
new
keyword suggests that the class is instantiated, which it isn't. I'd go for a static methodget()
orgetInstance()
like I do in Java. Jan 24, 2014 at 16:26 -
28@SethLadd this is very nice but I suggest it needs a couple points of explanation. There's the weird syntax
Singleton._internal();
that looks like a method call when it's really a constructor definition. There's the_internal
name. And there's the nifty language design point that Dart lets you start out (dart out?) using an ordinary constructor and then, if needed, change it to afactory
method without changing all the callers.– Jerry101May 8, 2014 at 22:36
Here is a comparison of several different ways to create a singleton in Dart.
1. Factory constructor
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 => _instance;
}
3. Static field
class SingletonThree {
SingletonThree._privateConstructor();
static final SingletonThree instance = SingletonThree._privateConstructor();
}
How to instantiate
The above singletons are instantiated like this:
SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;
Note:
I originally asked this as a question, but discovered that all of the methods above are valid and the choice largely depends on personal preference.
-
7I just upvoted your answer. Much more clear than the accepted answer. Just one more question: for the second and third way, what is the point of private constructor ? I saw many people did that, but I don't understand the point. I always simply use
static final SingletonThree instance = SingletonThree()
. The same goes to the second way for_instance
. I don't know what's disadvantage of not using a private constructor. So far, I don't find any problems in my way. The second and third ways are not blocking the call to default constructor anyway.– sgon00Mar 26, 2019 at 9:45 -
11@sgon00, the private constructor is so that you can't make another instance. Otherwise anyone could do
SingletonThree instance2 = SingletonThree()
. If you try to do this when there is a private constructor, you will get the error:The class 'SingletonThree' doesn't have a default constructor.
– SuragchMar 26, 2019 at 18:20 -
3what's the purpose of the
2
way vs3
? it does the same but adds verbosity with no reason. why to separate getter? Mar 7, 2021 at 22:05 -
1@nt4f04und in the example as given, there is no benefit to using a getter. however, you may wish to only instantiate the singleton upon first access, in which case, you could do so in the getter before returning
_instance
– Lee3Aug 24, 2021 at 7:16 -
2This answer is great. Thank you. For people out there wondering which way to choose, here's my opinion. I prefer method 3 and here's why. In method 1 you get an instance like this
final serviceInstance = Service()
In my opinion, it is not apparent that an existing instance will be used. So I preferfinal serviceInstance = Service.instance
, which makes it a lot more explicit.– HussainAug 28, 2022 at 14:23
Here is a simple answer:
- Class should have a
private
andstatic
property of its type. - The constructor should be
private
to prevent external object initialization. - Check if the instance is
null
, if yes create an instance and return it, otherwise return the existing instance.
Implementation (Factory Contractor)
class Singleton {
static Singleton? _instance;
Singleton._();
factory Singleton() => _instance ??= Singleton._();
void someMethod() {
// ...
}
}
Usage
Singleton().someMethod();
// prints "Same Singleton instance? true"
print('Same Singleton instance? ${Singleton().hashCode == Singleton().hashCode}');
Implementation (Lazy Loading)
class Singleton {
static Singleton? _instance;
Singleton._();
static Singleton get instance => _instance ??= Singleton._();
void someMethod() {
...
}
...
}
Implementation (Eager Loading)
class Singleton {
static Singleton _instance = Singleton._();
Singleton._();
static Singleton get instance => _instance;
void someMethod() {
...
}
...
}
Usage
Singleton.instance.someMethod();
-
6What's happening here? An explanation would earn you more points Mar 20, 2021 at 11:03
-
1For lazy loading, you should just be able to use the lazy keyword in newer versions of dart Oct 22, 2022 at 2:57
I don't find it very intuitive reading new Singleton()
. You have to read the docs to know that new
isn't actually creating a new instance, as it normally would.
Here's another way to do singletons (Basically what Andrew said above).
lib/thing.dart
library thing;
final Thing thing = new Thing._private();
class Thing {
Thing._private() { print('#2'); }
foo() {
print('#3');
}
}
main.dart
import 'package:thing/thing.dart';
main() {
print('#1');
thing.foo();
}
Note that the singleton doesn't get created until the first time the getter is called due to Dart's lazy initialization.
If you prefer you can also implement singletons as static getter on the singleton class. i.e. Thing.singleton
, instead of a top level getter.
Also read Bob Nystrom's take on singletons from his Game programming patterns book.
-
1This makes more sense to me, thanks to Greg and the feature of top-level property of dart.– Eason PIJul 8, 2016 at 3:00
-
This is no idiomatic. It is a dream feature to have a singleton pattern build in the language, and you are throwing it out because you are not used to it.– ArashMay 21, 2017 at 13:39
-
1Both Seth's example and this example are singleton patterns. It's really a question of syntax "new Singleton()" vs "singleton". I find the latter more clear. Dart's factory constructors are useful, but I don't think this is a good use case for them. I also think Dart's lazy initialisation is a great feature, which is underused. Also read Bob's article above - he recommends against singletons in most cases. May 21, 2017 at 20:41
-
I also recommend reading this thread on the mailing list. groups.google.com/a/dartlang.org/d/msg/misc/9dFnchCT4kA/… May 21, 2017 at 20:44
-
This is way better. The "new" keyword pretty heavily implies the construction of a new object. The accepted solution feels really wrong.– Sava B.Mar 17, 2019 at 15:19
What about just using a global variable within your library, like so?
single.dart
:
library singleton;
var Singleton = new Impl();
class Impl {
int i;
}
main.dart
:
import 'single.dart';
void main() {
var a = Singleton;
var b = Singleton;
a.i = 2;
print(b.i);
}
Or is this frowned upon?
The singleton pattern is necessary in Java where the concept of globals doesn't exist, but it seems like you shouldn't need to go the long way around in Dart.
-
11Top-level variables are cool. However, anyone who can imported single.dart is free to construct a "new Impl()". You could give a underscore constructor to Impl, but then code inside the singleton library could call that constructor. Sep 29, 2012 at 7:16
-
And the code in your implementation can't? Can you explain in your answer why it is better than a top level variable?– JanSep 29, 2012 at 8:40
-
2Hi @Jan, it's not better or worse, it's just different. In Andrew's example, Impl isn't a singleton class. He did correctly use a top-level variable to make the instance
Singleton
easy to access. In my example above, theSingleton
class is a real singleton, only one instance ofSingleton
can ever exist in the isolate. Sep 29, 2012 at 19:33 -
3Seth, you are not right. There is no way in Dart to build a true singleton, as there is no way of restricting instantiability of a class inside the declaring library. It always requires discipline from the library author. In your example, the declaring library can call
new Singleton._internal()
as many times as it wants, creating a lot of objects of theSingleton
class. If theImpl
class in Andrew's example was private (_Impl
), it would be the same as your example. On the other hand, singleton is an antipattern and noone should use it anyway.– LadicekSep 30, 2012 at 16:44 -
2@Ladicek, don't you trust the developers of a library not to call new
Singelton._internal()
. You can argue that the developers of the singelton class could instatiate the class several times as well. Sure there is the enum singelton but to me it is only of theoretic use. An enum is an enum, not a singelton... As for the use of top-level variables (@Andrew and @Seth): Couldn't anyone write to the top-level variable? It is by no means protected, or am I missing something? Oct 9, 2012 at 19:18
Here is another possible way:
void main() {
var s1 = Singleton.instance;
s1.somedata = 123;
var s2 = Singleton.instance;
print(s2.somedata); // 123
print(identical(s1, s2)); // true
print(s1 == s2); // true
//var s3 = new Singleton(); //produces a warning re missing default constructor and breaks on execution
}
class Singleton {
static final Singleton _singleton = new Singleton._internal();
Singleton._internal();
static Singleton get instance => _singleton;
var somedata;
}
Singleton that can't change the object after the instantiation
class User {
final int age;
final String name;
User({
this.name,
this.age
});
static User _instance;
static User getInstance({name, age}) {
if(_instance == null) {
_instance = User(name: name, age: age);
return _instance;
}
return _instance;
}
}
print(User.getInstance(name: "baidu", age: 24).age); //24
print(User.getInstance(name: "baidu 2").name); // is not changed //baidu
print(User.getInstance()); // {name: "baidu": age 24}
Dart singleton by const constructor & factory
class Singleton {
factory Singleton() =>
Singleton._internal_();
Singleton._internal_();
}
void main() {
print(new Singleton() == new Singleton());
print(identical(new Singleton() , new Singleton()));
}
-
2Hi, this code prints 2 x
false
in DartPad.dev. The instance needs to be null checked before returning a new one. Feb 2, 2021 at 9:00
In this example I do other things that are also necessary when wanting to use a Singleton. For instance:
- pass a value to the singleton's constructor
- initialize a value inside the constructor itself
- set a value to a Singleton's variable
- be able to access AND access those values.
Like this:
class MySingleton {
static final MySingleton _singleton = MySingleton._internal();
late String _valueToBeSet;
late String _valueAlreadyInSingleton;
late String _passedValueInContructor;
get getValueToBeSet => _valueToBeSet;
get getValueAlreadyInSingleton => _valueAlreadyInSingleton;
get getPassedValueInConstructor => _passedValueInContructor;
void setValue(newValue) {
_valueToBeSet = newValue;
}
factory MySingleton(String passedString) {
_singleton._valueAlreadyInSingleton = "foo";
_singleton._passedValueInContructor = passedString;
return _singleton;
}
MySingleton._internal();
}
Usage of MySingleton:
void main() {
MySingleton mySingleton = MySingleton("passedString");
mySingleton.setValue("setValue");
print(mySingleton.getPassedValueInConstructor);
print(mySingleton.getValueToBeSet);
print(mySingleton.getValueAlreadyInSingleton);
}
After reading all the alternatives I came up with this, which reminds me a "classic singleton":
class AccountService {
static final _instance = AccountService._internal();
AccountService._internal();
static AccountService getInstance() {
return _instance;
}
}
-
3I would change the
getInstance
method in aninstance
property like this:static AccountService get instance => _instance;
Oct 27, 2019 at 9:15 -
1i like this. since i want to add some thing before the instance is returned and other methods are used.– chitgoksJun 25, 2020 at 1:26
Here's a concise example that combines the other solutions. Accessing the singleton can be done by:
- Using a
singleton
global variable that points to the instance. - The common
Singleton.instance
pattern. - Using the default constructor, which is a factory that returns the instance.
Note: You should implement only one of the three options so that code using the singleton is consistent.
Singleton get singleton => Singleton.instance;
ComplexSingleton get complexSingleton => ComplexSingleton._instance;
class Singleton {
static final Singleton instance = Singleton._private();
Singleton._private();
factory Singleton() => instance;
}
class ComplexSingleton {
static ComplexSingleton _instance;
static ComplexSingleton get instance => _instance;
static void init(arg) => _instance ??= ComplexSingleton._init(arg);
final property;
ComplexSingleton._init(this.property);
factory ComplexSingleton() => _instance;
}
If you need to do complex initialization, you'll just have to do so before using the instance later in the program.
Example
void main() {
print(identical(singleton, Singleton.instance)); // true
print(identical(singleton, Singleton())); // true
print(complexSingleton == null); // true
ComplexSingleton.init(0);
print(complexSingleton == null); // false
print(identical(complexSingleton, ComplexSingleton())); // true
}
This is how I implement singleton in my projects
Inspired from flutter firebase => FirebaseFirestore.instance.collection('collectionName')
class FooAPI {
foo() {
// some async func to api
}
}
class SingletonService {
FooAPI _fooAPI;
static final SingletonService _instance = SingletonService._internal();
static SingletonService instance = SingletonService();
factory SingletonService() {
return _instance;
}
SingletonService._internal() {
// TODO: add init logic if needed
// FOR EXAMPLE API parameters
}
void foo() async {
await _fooAPI.foo();
}
}
void main(){
SingletonService.instance.foo();
}
example from my project
class FirebaseLessonRepository implements LessonRepository {
FirebaseLessonRepository._internal();
static final _instance = FirebaseLessonRepository._internal();
static final instance = FirebaseLessonRepository();
factory FirebaseLessonRepository() => _instance;
var lessonsCollection = fb.firestore().collection('lessons');
// ... other code for crud etc ...
}
// then in my widgets
FirebaseLessonRepository.instance.someMethod(someParams);
-
Congratulations for having the only entry in this long list of Singleton patterns with an async capability. The only thing missing from the approach to encompass all of the capabilities is a means of providing the
_internal()
function with some type of externally provided parameters.– oraveczMay 21, 2022 at 2:50
Since Dart 2.13
version, it is very easy with late
keyword. Late
keyword allows us to lazily instantiate objects.
As an example, you can see it:
class LazySingletonExample {
LazySingletonExample._() {
print('instance created.');
}
static late final LazySingletonExample instance = LazySingletonExample._();
}
Note: Keep in mind that, it will only be instantiated once when you call lazy
instance
field.
-
2In Dart, global variables and static class variables are lazy by default, so adding
late
to a static variable is superfluous. It is only when declaring a local variable aslate
that we can defer its initialization to when it's actually used.– bizz84Jun 22, 2022 at 9:30 -
Modified @Seth Ladd answer for who's prefer Swift style of singleton like .shared
:
class Auth {
// singleton
static final Auth _singleton = Auth._internal();
factory Auth() => _singleton;
Auth._internal();
static Auth get shared => _singleton;
// variables
String username;
String password;
}
Sample:
Auth.shared.username = 'abc';
If you happen to be using Flutter and provider
package for state management, creating and using a singleton is quite straightforward.
- Create an instance
void main() { runApp( MultiProvider( providers: [ ChangeNotifierProvider(create: (context) => SomeModel()), Provider(create: (context) => SomeClassToBeUsedAsSingleton()), ], child: MyApp(), ), ); }
- Get the instance
Widget build(BuildContext context) { var instance = Provider.of<SomeClassToBeUsedAsSingleton>(context); ...
Singleton
objects can be betterly created with null safety operator and factory constructor.
class Singleton {
static Singleton? _instance;
Singleton._internal();
factory Singleton() => _instance ??= Singleton._internal();
void someMethod() {
print("someMethod Called");
}
}
Usage:
void main() {
Singleton object = Singleton();
object.someMethod(); /// Output: someMethod Called
}
Note: ??
is a Null aware operator, it returns the right-side value if the left-side value is null, which means in our example _instance ?? Singleton._internal();
, Singleton._internal()
will be return first time when object gets called , rest _instance
will be return.
-
When will _instance be initialized? In your example _instance will always be null and _internal will be returned.– HerryNov 5, 2021 at 22:42
-
** Sigleton Paradigm in Dart Sound Null Safety**
This code snippet shows how to implement singleton in dart This is generally used in those situation in which we have to use same object of a class every time for eg. in Database transactions.
class MySingleton {
static MySingleton? _instance;
MySingleton._internal();
factory MySingleton() {
if (_instance == null) {
_instance = MySingleton._internal();
}
return _instance!;
}
}
how to create a singleton instance of a class in dart flutter
class ContactBook {
ContactBook._sharedInstance();
static final ContactBook _shared = ContactBook._sharedInstance();
factory ContactBook() => _shared;
}
-
excellent answer. can you also put in a reference from where you got this?– PramodJun 11, 2022 at 7:31
This is my way of doing singleton which accepts parameters (you can paste this directly on https://dartpad.dev/ ):
void main() {
Logger x = Logger('asd');
Logger y = Logger('xyz');
x.display('Hello');
y.display('Hello There');
}
class Logger{
Logger._(this.message);
final String message;
static Logger _instance = Logger._('??!?*');
factory Logger(String message){
if(_instance.message=='??!?*'){
_instance = Logger._(message);
}
return _instance;
}
void display(String prefix){
print(prefix+' '+message);
}
}
Which inputs:
Hello asd
Hello There asd
The '??!?*' you see is just a workaround I made to initialize the _instance variable temporarily without making it a Logger? type (null safety).
-
1I find this way of creating a singleton more useful since it can accept parameters Jun 22, 2022 at 19:12
Written cleanly.
The class can't be created more than once (using one instance automatically) which always enforces correct use 😄.
.
class A {
factory A() {
return _instance;
}
A._singletonContractor(){
print('Will be called once when object created');
}
static final A _instance = A._singletonContractor();
}
void main() {
var a1 = A();
var a2 = A();
print(identical(a1, a2)); // true
print(a1 == a2); // true
}
This should work.
class GlobalStore {
static GlobalStore _instance;
static GlobalStore get instance {
if(_instance == null)
_instance = new GlobalStore()._();
return _instance;
}
_(){
}
factory GlobalStore()=> instance;
}
-
Please don't post follow-up questions as answers. The issue with this code is that it is a bit verbose.
static GlobalStore get instance => _instance ??= new GlobalStore._();
would do. What is_(){}
supposed to do? This seems redundant. Oct 13, 2018 at 8:35 -
sorry, that was a suggestion, not a follow up question, _(){} will create a private constructor right ? Oct 13, 2018 at 8:40
-
Constructors start with the class name. This is just a normal private instance method without a return type specified. Oct 13, 2018 at 8:42
-
1Sorry for the downvote, but I think it's poor quality and doesn't add any value in addition to the existing answers. Oct 13, 2018 at 9:30
-
2While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Oct 14, 2018 at 8:55
As I'm not very fond of using the new
keyword or other constructor like calls on singletons, I would prefer to use a static getter called inst
for example:
// the singleton class
class Dao {
// singleton boilerplate
Dao._internal() {}
static final Dao _singleton = new Dao._internal();
static get inst => _singleton;
// business logic
void greet() => print("Hello from singleton");
}
example usage:
Dao.inst.greet(); // call a method
// Dao x = new Dao(); // compiler error: Method not found: 'Dao'
// verify that there only exists one and only one instance
assert(identical(Dao.inst, Dao.inst));
Hello what about something like this? Very simple implementation, Injector itself is singleton and also added classes into it. Of course can be extended very easily. If you are looking for something more sophisticated check this package: https://pub.dartlang.org/packages/flutter_simple_dependency_injection
void main() {
Injector injector = Injector();
injector.add(() => Person('Filip'));
injector.add(() => City('New York'));
Person person = injector.get<Person>();
City city = injector.get<City>();
print(person.name);
print(city.name);
}
class Person {
String name;
Person(this.name);
}
class City {
String name;
City(this.name);
}
typedef T CreateInstanceFn<T>();
class Injector {
static final Injector _singleton = Injector._internal();
final _factories = Map<String, dynamic>();
factory Injector() {
return _singleton;
}
Injector._internal();
String _generateKey<T>(T type) {
return '${type.toString()}_instance';
}
void add<T>(CreateInstanceFn<T> createInstance) {
final typeKey = _generateKey(T);
_factories[typeKey] = createInstance();
}
T get<T>() {
final typeKey = _generateKey(T);
T instance = _factories[typeKey];
if (instance == null) {
print('Cannot find instance for type $typeKey');
}
return instance;
}
}
Easy as that:
class Singleton {
Singleton._();
static final _uniqueInstance = Singleton._();
factory Singleton() => _uniqueInstance;
}
void singleton() {
final mysingleton = Singleton();
}
Or honoring Smalltalk:
class Singleton {
Singleton._();
static final Singleton uniqueInstance = Singleton._();
}
void singleton() {
final mysingleton = Singleton.uniqueInstance();
}
I use this simple pattern on dart and previously on Swift. I like that it's terse and only one way of using it.
class Singleton {
static Singleton shared = Singleton._init();
Singleton._init() {
// init work here
}
void doSomething() {
}
}
Singleton.shared.doSomething();
This is also a way to create a Singleton class
class Singleton{
Singleton._();
static final Singleton db = Singleton._();
}
Create Singleton
class PermissionSettingService {
static PermissionSettingService _singleton = PermissionSettingService._internal();
factory PermissionSettingService() {
return _singleton;
}
PermissionSettingService._internal();
}
Reset Singleton
// add this function inside the function
void reset() {
_singleton = PermissionSettingService._internal();
}
There is nothing tricky about creating a Singleton in Dart. You can declare any variable in a top-level (global) location, which is a Singleton by default. You can also declare a variable as a static member of a class. This is a singleton A
.
class A {}
final a = A();
However, the above does not allow you to replace the instance for testing. The other issue is that as the app grows in complexity, you may want to convert global or static variables to transient dependencies inside your classes. If you use dependency injection, you can change a dependency inside your composition at any time. This is an example of using ioc_container to configure a singleton instance of A
in the root of an app. You can change this to a transient dependency any time by using add
instead of addSingletonService
import 'package:ioc_container/ioc_container.dart';
class A {}
void main(List<String> arguments) {
final builder = IocContainerBuilder()..addSingletonService(A());
final container = builder.toContainer();
final a1 = container<A>();
final a2 = container<A>();
print(identical(a1, a2));
}
The above prints true
because the app will only ever mint one instance of A
.
-
1
-
In Flutter, a singleton class is a class that allows you to create only one instance throughout the lifetime of your application. Singletons are often used to manage global state or to ensure that there is only one instance of a particular class. You can implement a singleton in Flutter using the following code pattern -
class MySingleton {
// Private constructor
MySingleton._privateConstructor();
// The single instance of the class
static final MySingleton _instance = MySingleton._privateConstructor();
// Factory constructor to provide access to the instance
factory MySingleton() {
return _instance;
}
// Add your methods and properties here
}
void main() {
MySingleton instance1 = MySingleton();
MySingleton instance2 = MySingleton();
print(identical(instance1, instance2)); // This will print 'true' since it's the same instance.
}
For creating singleton object you can use get_it package.
To create singleton:
GetIt.I.registerSingleton(YourClass());
To get singleton object:
GetIt.I<YourClass>()