The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?
-
1I 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 Nishad May 31 '20 at 19:31
-
because static instance is lazy initialized by default in Dart – Mohammad Alotol Mar 19 '22 at 18:57
27 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? – westoque May 29 '13 at 06:30
-
119I'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". – Seth Ladd May 29 '13 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 03 '13 at 14:29
-
I found all the solution here works only for using native dart vm. Once it compiles to js, if you import it in different libraries, you get different instances. I'm using dart 1.0; – yi chen Jan 24 '14 at 02:16
-
16It'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 method `get()` or `getInstance()` like I do in Java. – Steven Roose Jan 24 '14 at 16:26
-
-
@SethLadd Nope. I included the same URI for the global library, but it gives me different instances. I checked the hashcode. – yi chen Jan 25 '14 at 23:22
-
1@StevenRoose I don't think the client code must be aware of using or not a singleton: this is an implementation choice. With the 'getInstance()' static method you know that you'll use a singleton!I agree that's a bit confusing but what about if you decide to change your singleton for something else? If you used the 'getInstance()' static method, then you need to change your code everywhere you used it! With the 'new Singleton()' ther's no change. – Eric Taix Feb 17 '14 at 13:21
-
24@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 a `factory` method without changing all the callers. – Jerry101 May 08 '14 at 22:36
-
Is it possible to build a `const` singleton? (`const factory` constructors must be redirecting factory constructors.) - P.S.: Within its library multiple instances can be created by calling `new Singleton._internal();`, unlikely as that may be. – Ganymede Mar 21 '15 at 14:28
-
Really nice, but how do we pass parameters to the factory @SethLadd? Like in JAVA we would need to pass parameters in order to create a custom singleton and then use this in-memory object created only once. – R. Karlus Apr 01 '19 at 14:37
-
1This is certainly one way to implement singletons in Dart, but using a factory is just going to make people confused by the constructor syntax. IMO it would be better to have a public `static final` instance that is instantiated by a private constructor. – Abion47 May 05 '19 at 20:21
-
2@Ganymede If the constructor for the singleton is constant, then you can have the singleton instance be constant as well. Just know that in order to do this, the class cannot have any state. (i.e. All fields must be marked as final and initialized in the constructor or at declaration using only other constants.) – Abion47 May 05 '19 at 20:24
-
I don't like this approach, because from outside code getting instance of Singleton doesn't look different from creating instance of any object. Which make code less readable. When i see `SomeObj.instance` or `SomeObj.getInstance(OtherObj parameter)` I understand that I'm dealing with singleton. – Artem_Iens Jul 22 '20 at 04:40
-
-
There is a popular saying that goes: 'When in Rome, Do as the Romans Do'. I come from the place of C# that every constructor must have the 'new' keyword. Now I develop on as well on Dart, so I don't see why I should not follow the pattern used there IMHO. – Wizzyno Aug 26 '22 at 06:18
-
-
@SethLadd I'm using this function to reset singleton class when I needed. is it good practice to do it? and is it okay to do this way? `void reset() {` ` _singleton = PermissionSettingService._internal();` `}` – BIS Tech Sep 19 '22 at 16:58
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.

- 484,302
- 314
- 1,365
- 1,393
-
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. – sgon00 Mar 26 '19 at 09: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.` – Suragch Mar 26 '19 at 18:20
-
3what's the purpose of the `2` way vs `3`? it does the same but adds verbosity with no reason. why to separate getter? – nt4f04und Mar 07 '21 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` – Lee3 Aug 24 '21 at 07:16
-
@Suragch Would be clear for many developers if you provided usage examples – K.Amanov Oct 17 '21 at 14:04
-
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 prefer `final serviceInstance = Service.instance`, which makes it a lot more explicit. – Hussain Aug 28 '22 at 14:23
-
It's really good to find answers that have options and explanations. Thank you! But I still have a question, how do I destroy the instance? For example, I want my instance to get destroyed when user leaves view and created again when user access view again. – JAgüero Dec 06 '22 at 12:42
-
@parkorian In that case, you don't want a singleton. You can just use a normal class with a normal constructor inside your stateful widget (if you are using Flutter). `class MyClass { }` and `final myInstance = MyClass();`. The Dart garbage collector will take care of freeing up the memory associated with the old instance when you leave the view. – Suragch Dec 08 '22 at 06:44
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();

- 5,867
- 4
- 32
- 56
-
5What's happening here? An explanation would earn you more points – Ojonugwa Jude Ochalifu Mar 20 '21 at 11:03
-
1For lazy loading, you should just be able to use the lazy keyword in newer versions of dart – Gregory Conrad Oct 22 '22 at 02: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 PI Jul 08 '16 at 03: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. – Arash May 21 '17 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. – Greg Lowe May 21 '17 at 20:41
-
I also recommend reading this thread on the mailing list. https://groups.google.com/a/dartlang.org/d/msg/misc/9dFnchCT4kA/AG6vb1fZDREJ – Greg Lowe May 21 '17 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 '19 at 15:19
-
FWIW, `new` is no longer necessary in Dart 2, and its usage is now discouraged, partly because its usage with a factory constructor was misleading. – jamesdlin Mar 28 '19 at 23:56
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.

- 112,095
- 66
- 196
- 279
-
10Top-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. – Seth Ladd Sep 29 '12 at 07:16
-
And the code in your implementation can't? Can you explain in your answer why it is better than a top level variable? – Jan Sep 29 '12 at 08: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, the `Singleton` class is a real singleton, only one instance of `Singleton` can ever exist in the isolate. – Seth Ladd Sep 29 '12 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 the `Singleton` class. If the `Impl` 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. – Ladicek Sep 30 '12 at 16:44
-
1@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? – Tobias Ritzau Oct 09 '12 at 19:18
-
Thank you @Ladicek you are correct, a developer can call `Singleton._internal()` if inside the library and thus create new instances. – Seth Ladd Oct 16 '12 at 03:39
-
This is easier to understand with fewer statements, for someone new. Thanks. I was/am using 'scopedmodel' to store variables that are required elsewhere. – Ant D Feb 01 '19 at 09:22
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;
}

- 1,460
- 3
- 14
- 20
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}

- 492
- 3
- 12

- 1,515
- 11
- 15
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()));
}

- 344
- 3
- 17

- 377
- 2
- 6
-
2Hi, this code prints 2 x `false` in DartPad.dev. The instance needs to be null checked before returning a new one. – ǝlpoodooɟƃuooʞ Feb 02 '21 at 09: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();
String _valueToBeSet;
String _valueAlreadyInSingleton;
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);
}

- 3,878
- 31
- 44
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;
}
}

- 18,900
- 15
- 104
- 159
-
3I would change the `getInstance` method in an `instance` property like this: `static AccountService get instance => _instance;` – gianlucaparadise Oct 27 '19 at 09:15
-
1i like this. since i want to add some thing before the instance is returned and other methods are used. – chitgoks Jun 25 '20 at 01: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
}

- 8,841
- 3
- 51
- 66
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);

- 4,551
- 1
- 30
- 24
-
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. – oravecz May 21 '22 at 02: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.

- 670
- 8
- 20
-
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 as `late` that we can defer its initialization to when it's actually used. – bizz84 Jun 22 '22 at 09: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';

- 3,513
- 27
- 23
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); ...

- 4,115
- 38
- 29
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.

- 31,138
- 12
- 157
- 147
-
When will _instance be initialized? In your example _instance will always be null and _internal will be returned. – Herry Nov 05 '21 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!;
}
}

- 121
- 1
- 5
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;
}

- 6,024
- 6
- 41
- 60
-
excellent answer. can you also put in a reference from where you got this? – Pramod Jun 11 '22 at 07: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).

- 509
- 1
- 6
- 15
-
1I find this way of creating a singleton more useful since it can accept parameters – Phillip Rekhotho Jun 22 '22 at 19:12
This should work.
class GlobalStore {
static GlobalStore _instance;
static GlobalStore get instance {
if(_instance == null)
_instance = new GlobalStore()._();
return _instance;
}
_(){
}
factory GlobalStore()=> instance;
}

- 69,473
- 35
- 181
- 253

- 1,529
- 14
- 23
-
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. – Günter Zöchbauer Oct 13 '18 at 08:35
-
sorry, that was a suggestion, not a follow up question, _(){} will create a private constructor right ? – Vilsad P P Oct 13 '18 at 08:40
-
Constructors start with the class name. This is just a normal private instance method without a return type specified. – Günter Zöchbauer Oct 13 '18 at 08:42
-
1Sorry for the downvote, but I think it's poor quality and doesn't add any value in addition to the existing answers. – Günter Zöchbauer Oct 13 '18 at 09: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. – Kalle Richter Oct 14 '18 at 08: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));

- 66
- 1
- 6
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;
}
}

- 75
- 1
- 8
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();

- 1,436
- 1
- 11
- 20
This is also a way to create a Singleton class
class Singleton{
Singleton._();
static final Singleton db = Singleton._();
}

- 1,097
- 1
- 16
- 26
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();
}

- 17,000
- 12
- 99
- 148
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
.

- 6,770
- 5
- 51
- 103
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.

- 7
- 2
-
1The issue with const. is that your singleton will not be able to have state that is changed – CloudBalancing Jul 13 '21 at 16:27
-
@CloudBalancing You can just use static variables for the state. – Salvatore Gerace Jul 15 '21 at 07:37
-
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. – scrimau Mar 20 '22 at 17:17