Skip to main content

Command Palette

Search for a command to run...

Singleton Guide for New Bees in Flutter

Published
4 min read
Singleton Guide for New Bees in Flutter
R

I'm Renga, a Flutter developer passionate about building efficient and scalable apps. I share whatever I learn with the world every weekend, covering insights, best practices, and real-world solutions to help developers master Flutter. Let’s learn and build together!

Hi my Flutter dev people, today I am going to share,

  • What is a singleton?

  • Why singleton?

  • How to create a singleton using Dart?

  • 1. Ex with explanation.

Initially, during my college days mini projects, I wanted to store some data in my app. I'm not aware of how to store some values and pass them throughout the app. I created a class, created an instance, and used it. But each time it returns a new instance, the new instance has no values. I was totally upset. That time I Googled it, I learned “singleton concept“ in Flutter.


What is a Singleton?

  • Imagine you have a bag. You can put and take things wherever you're from. This is exactly what a singleton is.

  • Here, you have a class; we are able to create a multiple instance to access the respective class’s properties and methods. But the magic is, it returns the same instance every time.

  • Even if you create 5 instances, all 5 instances will be the same.

  • Finally, Singleton ensures that the class has only one instance and provides a global point of access to it.


Why Singleton?

  • If you want to share the data across your entire app, the best choice is Singleton.

  • If you have a question like, In which scenarios will it be best to use and more helpful? (Ha.. Haaa.. I got your question!)


Scenarios:

Scenario 1: Database Connections:

Without using Singleton

  • Imagine you are going to connect openDatabase()to a local database.

  • Here, each time you will call opneDatabase()multiple times.

  • It leads to creating multiple databases in the same location and memory leaks.

Solution

  • Use Singleton to fix the issue.

  • Why? Because singleton will return only one instance all the time.

Scenario 2: API Clients/Network service (e.g., Dio || Http)

Without using Singleton

  • You will create new instance for each API call

  • You can not manage the exceptions and tokens wisely for each API call.

  • You can not handle the headers and interceptors.

Solution

  • If you create the NetworManagerclass with a singleton, the issue will be fixed.

Scenario 3: User Session

Without using Singleton

  • We want to share the logged-user information like [name, mail, token] throughout the app. This is what we want.

  • But we can't achieve this without a singleton.

Solution

  • Use a singleton to share the user details in the entire app.

How to create a Singleton in Flutter/Dart?

  • It’s easy; we need only 3 ingredients.

    1. A static final private instance.

    2. A private named constructor.

    3. A public factory constructor.

//* Creating Singlton
class MySingleton {
  // 1. Create a static private instance
  static final MySingleton _instance = MySingleton._internal();

  // 2. Private constructor
  MySingleton._internal();

  // 3. Public factory constructor that returns the same instance
  factory MySingleton() {
    return _instance;
  }

  void sayHello() {
    print('Hello from Singleton!');
  }
}

//* Usage
void main() {
  var obj1 = MySingleton();
  var obj2 = MySingleton();

  print(obj1 == obj2); // true
  obj1.sayHello(); // Hello from Singleton!
}

As a compiler, I will explain it step by step.

Step 1:

  • mainexecutes first.

Step 2:

  • MySingleton();will execute.

  • Which means it is a factory constructor.

  • So it will return the existing instance (not create a new instance)

  • But here the _instance is not initially.

Step 3:

  • Now, the _instance is not initialized, so the system starts to initialize it (call the MySingleton._internal();private constructor) and store it in a_instance variable.

  • This is a static variable. So, it creates an instance only for the class, not for each objects.

  • And also, it’s final, so no one is able to reassign the value once it’s initialized.

Step 4:

  • Now, the _instance has value, so the factory constructor is ready to return the respective value.

  • So, now, the obj1get the value.

Step 5:

  • Similarly, the same flow will happen for obj2 as well.

  • But, here, the system has the _instance value already.

  • So, the system won’t call the private constructor again. Which means the private constructor won’t execute now. It will execute only one time (the very first time).

  • Then, obj2 gets the value.

Step 6:

  • After that, the system compares obj1andobj2

  • Both are the same instance, so the system returns true as a result of the operation.

Step 7:

  • Then call the function by using the obj1variable.

  • It will return the Hello from Singleton!

  • That’s all!


Conclusion:

  • Singleton shares the data all over the app.

  • It doesn’t create a new instance for each object creation.

  • It only returns the same already existing instance.

  • We can't reassign from outside of the class once the instance is created.

  • If we create multiple objects the singleton class only returns the same instance, So if we compare it, it will be gets true.