How to Build a Singleton In Dart

How to Build a Singleton In Dart?

Only one instance of a class is created in a singleton pattern. So in this article, we will go through how to Build a Singleton In Dart.

How to Build a Singleton In Dart?

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

Firstly, You can construct it like this

main() {
  var s1 = Singleton();
  var s2 = Singleton();
  print(identical(s1, s2));  // true
  print(s1 == s2);           // true
}

But what about just using a global variable within your library.

Single.dart will have a code snippet like the below:

library singleton;
var singleton = Impl();
class Impl {
  int? i;
}

main.dart

import 'single.dart';

void main() {
  var a = Singleton;
  var b = Singleton;
  a.i = 2;
  print(b.i);
}

Also, look at the 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()));
}

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

Moreover, 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.

Also, consider a code snippet like the below:

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

But what 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
}
  • Factory constructor

    class SingletonOne {
      SingletonOne._privateConstructor();
      static final SingletonOne _instance = SingletonOne._privateConstructor();
      factory SingletonOne() {
        return _instance;
      }
    }
  • Static field with getter

    class SingletonTwo {
      SingletonTwo._privateConstructor();
      static final SingletonTwo _instance = SingletonTwo._privateConstructor();
      static SingletonTwo get instance => _instance;
    }
  • Static field

    class SingletonThree {
      SingletonThree._privateConstructor();
      static final SingletonThree instance = SingletonThree._privateConstructor();
      
    }

    How to instantiate

    The above singletons are instantiated as below:

    SingletonOne one = SingletonOne();
    SingletonTwo two = SingletonTwo.instance;
    SingletonThree three = SingletonThree.instance;

Conclusion:

Thanks for Reading!

So, In this article, we have been through how to Build a Singleton In Dart.

So, Keep Learning! Keep Fluttering!

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number