How do you build a Singleton in Dart?

The Singleton pattern is a pattern used in object-oriented programming which ensures that a class has only one instance and also provides a global point of access to it. The first and foremost reason to use Singleton in any programming language is to replace the redundant code with a single line command. So, specifically talking about Dart (or cross-platform mobile app development tool, Flutter) there are many screens where we need to show a snack bar or a confirmation dialogue to the user. As a freshie, everyone is going to write a code to show a snack bar as shown below.

How to Create Singleton in Dart 1 Sunflower lab

Just to show a single component, you’ll have to write this many lines. The number of lines in a single dart file increase drastically. And when a minor change comes from a design point of view, you’ll have to make those changes in all the files where you’ve used a snack bar.

The solution to this kind of problems is a singleton class, where we can define the most commonly used codes throughout the project and reuse it whenever needed.

Ways to Create a Singleton Class

There are mainly 3 ways to create a Singleton class:

  1. Factory Constructor
  2. Static Fields with a Getter
  3. Only Static Fields

We’ll first take a look on the most preferred and commonly-used way: Factory Constructor.

How to Create Singleton in Dart

As you can see on line number no. 8, we defined a private constructor to which the memory will get allotted. Secondly, we created a private constructor to allocate the memory. Now comes the interesting part of the factory keyword. Once instantiated, it will always return the same instance whenever any public variable or method is called.

Let’s start with defining global variables in the singleton class. We are going to define this global variable in the ViewUtilities just like any other variable we define in other classes.

How To Create Singleton In Dart

Moving forward with using this variable throughout the whole app, we just need to call the variable using the `.` operator i.e., as follows.

How To Create Singleton In Dart

Awesome! Just like variables, we can also define methods that can be used throughout the whole app.

For the demonstration purpose, we’ll define a public method in our singleton class to multiply 2 digits and return the result as shown below.

How To Create Singleton In Dart

Now that we have defined the public methods in our singleton class, we are going to access the multiply method in the similar way that we access the appName variable i.e., using the `. ` operator.

How To Create Singleton In Dart

This was the basic implementation of singleton class in dart. We hope you found this article helpful. Stay connected for our future small but unique articles on programming best practices. Happy coding!