Dart/Flutter – How to create Singleton

As you already know, a Singleton class is a class that can have only ONE/SINGLE instance at a time. When we try to create a new instance, it will reuse or point to the created instance. In this post, we go through some different approaches to create Singleton in Dart/Flutter.

1. Using public static field

class SingletonUsingStaticField {
  SingletonUsingStaticField._private();

  static final SingletonUsingStaticField instance =
      SingletonUsingStaticField._private();
}
void main() {
  // Using public static field
  SingletonUsingStaticField singletonUsingStaticField1 =
      SingletonUsingStaticField.instance;
  SingletonUsingStaticField singletonUsingStaticField2 =
      SingletonUsingStaticField.instance;
  print(singletonUsingStaticField1 == 
  singletonUsingStaticField2); // true
}

2. Using private static field and getter

class SingletonUsingStaticFieldAndGetter {
  SingletonUsingStaticFieldAndGetter._private();

  static final SingletonUsingStaticFieldAndGetter _instance =
      SingletonUsingStaticFieldAndGetter._private();

  static SingletonUsingStaticFieldAndGetter get instance => _instance;
}
void main() {
  // Using private static field and getter
  SingletonUsingStaticFieldAndGetter singletonUsingStaticFieldAndGetter1 =
    SingletonUsingStaticFieldAndGetter.instance;
  SingletonUsingStaticFieldAndGetter singletonUsingStaticFieldAndGetter2 =
    SingletonUsingStaticFieldAndGetter.instance;
  print(singletonUsingStaticFieldAndGetter1 ==
    singletonUsingStaticFieldAndGetter2); // true
}

3. Using private static field and factory constructor

class SingletonUsingFactoryConstructor {
  SingletonUsingFactoryConstructor._private();

  static final SingletonUsingFactoryConstructor _instance =
      SingletonUsingFactoryConstructor._private();

  factory SingletonUsingFactoryConstructor() {
    return _instance;
  }
}
void main() {
  // Using private static field and Factory constructor
  SingletonUsingFactoryConstructor singletonUsingFactoryConstructor1 =
    SingletonUsingFactoryConstructor();
  SingletonUsingFactoryConstructor singletonUsingFactoryConstructor2 =
    SingletonUsingFactoryConstructor();
  print(singletonUsingFactoryConstructor1 == 
    singletonUsingFactoryConstructor2); // true
}

You can find full source code on my Github.

Tagged : / / /
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x