Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Explore Singleton Design Pattern In Flutter

One of the most widely used design patterns for software development is the Singleton pattern. It is a creational design pattern that is used to make things. If you’re unsure what a design pattern is, look at my earlier articles on the design pattern series.

This blog will Explore Singleton Design Pattern In Dart. We see how to execute a demo program in your applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

What is the Singleton Design Pattern?

When to use?

How to implement in Dart?

Demo of Singleton in Flutter

Drawbacks

Conclusion



What is the Singleton Design Pattern?:

The Singleton design pattern, as described in the book “Design Patterns, Elements of Reusable Object-Oriented Software,” ensures that a class only has one instance and provides a global point of access to it.

Let’s simplify the situation. By referring to this one instance of the class as a “global point of access,” we mean that it is possible to access it from any location within the code without having to build a new instance.

A design guideline known as the Singleton Pattern restricts a class to a single instance. It assures that there is only one instance of the class in existence at any one time and that there is only one object of that class.

When only one object is required to coordinate actions throughout the system, this design is extremely helpful. It offers a mechanism to manage who has access to shared resources, like files or databases.

When to use?:

When managing a single resource, having singletons is helpful. Here are a few as examples.

  1. Configuration Management: To save settings and configurations that are consistent across the application, the singleton design is helpful. It guarantees consistency by directing all application components to a single source of configuration.
  2. Database Connection Pools: To guarantee that database connections are controlled from a single location, a singleton might be employed. This minimises conflicts brought on by multiple connection points and enables more effective use of database resources.
  3. Logging: A centralised, application-wide logging system that guarantees all log entries are consistently transmitted to a single repository is made possible by implementing a logging service as a singleton.
  4. State Management: A standardised and centralised way to access and update global application states, like user sessions, can be handled via singletons.
  5. Registry Settings: Access to registry settings can be managed with a singleton. This ensures that the settings are shown uniformly throughout the program.
  6. Load Balancers: A load balancer that divides network or application traffic among several servers can be made with singletons. This guarantees that traffic is managed by a single instance of the load balancer.
  7. File Manager: An application’s file operations can be managed by a singleton. By doing this, possible conflicts are avoided and all file read/write operations are centralised.

How to implement in Dart?

Let’s now attempt to implement the Dart singleton design pattern. To help you better comprehend the code, I’ll divide it up into several sections.

=> Create a class

In order to make things obvious, I’m using the term Singleton, but you can call it anything. _internal() is its private constructor. By doing this, it is made sure that no more Singleton instances are created from outside the class.

class Singleton {
  static Singleton? _instance;
  Singleton._internal();

=> Create the Singleton class instance

To check if _instance is null, we then create a getter instance. In that case, a new Singleton instance is created and set to _instance. The current Singleton instance is returned if _instance is not null.

static Singleton get instance {
    if (_instance == null) {
      _instance = Singleton._internal();
    }
    return _instance!;
  }

=> Add the functionality to your singleton class

We will now give the Singleton class more features. We’ve included an increment() method and a counter variable in this situation. The counter is simply increased by one using the increment() technique.

int counter = 0;

  void increment() {
    counter++;
  }
}

=> Use the Singleton

Lastly, we utilise the Singleton in our main() function. After obtaining the Singleton instance, we print the counter value using its increment() method.

void main() {
  Singleton singleton = Singleton.instance;
  singleton.increment();
  print("Counter = ${singleton.counter}");
}

The counter will rise by one each time you execute this code. This demonstrates that, regardless of where we are in the code, we are always working with the same Singleton instance.

Demo of Singleton in Flutter:

We’ll create a UserPreference Singleton class in order to create a user preference class that uses the shared_preference package to store data locally. In a Flutter application, this class offers a centralised, effective method for handling user preferences.

import 'package:shared_preferences/shared_preferences.dart';

class UserPreferences {
  static UserPreferences? _instance;

  UserPreferences._internal();

  static UserPreferences get instance {
    if (_instance == null) {
      _instance = UserPreferences._internal();
    }
    return _instance!;
  }

  late SharedPreferences _preferences;

  Future<void> init() async {
    _preferences = await SharedPreferences.getInstance();
  }

  String get username => _preferences.getString('username') ?? '';

  set username(String value) {
    _preferences.setString('username', value);
  }
}

It guarantees that there is only a single instance of the class and that user preferences are maintained between app launches. We will also attempt to obtain and configure the username.

=> main.dart

// The main function of the application.
void main() async {
  // Ensures that you have an instance of the WidgetsBinding.
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize the UserPreferences singleton instance.
  await UserPreferences.instance.init();

  // Run the app. The const keyword here means that the MyApp widget is
  runApp(const MyApp());
}

Drawbacks:

  1. Global State: Singletons can introduce hard-to-detect dependencies between classes and make an application difficult to understand by creating a global state.
  2. Difficulty in Testing: Because singletons maintain state throughout the lifecycle of the program, they can make unit testing challenging. Tests can interact with one another and cannot be separated due to this shared state.
  3. Memory Usage: Until the program is closed, a Singleton class instance stays in memory after it has been formed. This could consume more memory than is necessary, especially if the instance is large and won’t be used for the duration of the application.
  4. Inflexibility: Programming can become rigid and closely linked due to singletons, which makes it more challenging to modify and expand the code.
  5. Misinterpretation: When the getInstance function is changed to accept parameters, it’s simple to inadvertently turn a singleton into a factory design.

Conclusion:

In the article, I have explained the Singleton Design Pattern basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to the Singleton Design Pattern On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on trying the Explore Singleton Design Pattern In Flutter in your projects. One essential idea that software developers must comprehend is the Singleton design pattern. It provides a special and efficient method of controlling worldwide resource access. The Singleton design, suitable use cases, Dart implementation, and possible disadvantages are all covered in this article.

The UserPreferences class, which effectively manages user preferences by maintaining a single instance of the class, serves as another example of its useful implementation in Flutter. Notwithstanding its advantages, it’s important to take into account the possible drawbacks of Singleton, including testing issues, global state management, and possible rigidity in code modification. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

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