ChatGPT解决这个技术问题 Extra ChatGPT

How do you build a Singleton in Dart?

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

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
because static instance is lazy initialized by default in Dart

S
Suragch

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
}

Although 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?
I'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".
What exactly does the factory keyword serve over here? It is purely annotating the implementation. Why is it required?
It'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.
@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.
S
Suragch

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.


I 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, 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.
what's the purpose of the 2 way vs 3? it does the same but adds verbosity with no reason. why to separate getter?
@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
@Suragch Would be clear for many developers if you provided usage examples
H
Hamed

Here is a simple answer:

first of all, we need a private and static property of class type.

secondly, the constructor should be private, because we want to prevent object initialization from outside of the class.

and finally, we check instance nullability, if it is null we will instantiate and return it, else we will return the already instantiated instance.

Implementation with Lazy Loading

class Singleton {
  static Singleton? _instance;

  Singleton._();

  static Singleton get instance => _instance ??= Singleton._();

  void someMethod(){
    ...
  }

  ...
}

Implementation with Eager Loading

class Singleton {
  static Singleton _instance = Singleton._();

  Singleton._();

  static Singleton get instance => _instance;

  void someMethod(){
    ...
  }

  ...
}

Usage

Singleton.instance.someMethod();

What's happening here? An explanation would earn you more points
j
jamesdlin

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.


This makes more sense to me, thanks to Greg and the feature of top-level property of dart.
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.
Both 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.
I also recommend reading this thread on the mailing list. groups.google.com/a/dartlang.org/d/msg/misc/9dFnchCT4kA/…
This is way better. The "new" keyword pretty heavily implies the construction of a new object. The accepted solution feels really wrong.
S
Seth Ladd

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.


Top-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.
And the code in your implementation can't? Can you explain in your answer why it is better than a top level variable?
Hi @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, 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, 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?
i
iBob101

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;
}

s
shinriyo

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()));
}

Hi, this code prints 2 x false in DartPad.dev. The instance needs to be null checked before returning a new one.
I
Iván Yoed

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);

}

i
iamdipanshus

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}

t
thisisyusub

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.


In 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.
late doesn't convert a class in a singleton
d
daveoncode

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;
  }
}

I would change the getInstance method in an instance property like this: static AccountService get instance => _instance;
i like this. since i want to add some thing before the instance is returned and other methods are used.
s
sultanmyrza

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.
J
Jacob Phillips

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
}

D
DazChong

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';

M
Maxim Saplin

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(context); ...


E
Eric Aya

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.
sorry, that was a suggestion, not a follow up question, _(){} will create a private constructor right ?
Constructors start with the class name. This is just a normal private instance method without a return type specified.
Sorry for the downvote, but I think it's poor quality and doesn't add any value in addition to the existing answers.
While 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.
s
sprestel

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));

F
Filip Jerga

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;
  }
}

A
Aman Ansari

** 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!;
  }
}

J
Jitesh Mohite

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.
@Herry: Thanks for commenting, I missed to use '=' operator.
c
cattarantadoughan

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).


I find this way of creating a singleton more useful since it can accept parameters
J
Javeed Ishaq

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?
G
George Yacoub

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();

A
Ajanyan Pradeep

This is also a way to create a Singleton class

class Singleton{
  Singleton._();
  static final Singleton db = Singleton._();
}

S
Salvatore Gerace

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.


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.