Search code examples
flutterdartconfigurationsingleton

How to have a global singleton object in Flutter App


I would like a singleton object (i.e ConfigManager) able to return a configuration object (e.g. EnglishLocale) and keep it available for the whole application life cycle. Let's make an Example :

  1. The first time a user start the app, he is asked to choose the default language (e.g english, french, italian...).
  2. A ConfigManager singleton is created on-the-fly and binded to a Locale object (that contains all the hard coded strings in that language).

When i need a specific string i just have to do something like

ConfigManager.instance.locale.myString;

Now, i've looked here in order to understand how things work in Dart. The Singleton creation part is clear, however i need to provide different configurations based on user input as i said.

Have a look at the following image for a more schematic view:

enter image description here

Edit 1, Now, this is what i've done so far:

class ConfigManager {
  Locale loc;
  static ConfigManager _instance;
  factory ConfigManager(Locale loc) => _instance ??= new ConfigManager._(loc);

  ConfigManager._(Locale loc);

  static get instance => _instance;
}

In this way i can use the following syntax when i decide to get one specific string :

ConfigManager.instance.loc.presentation1body

And this is the initialization phase

ConfigManager(new EnglishLocale());

However i continue to get the error

"the getter was called on null"

I'm a little bit confused, please help me.


Solution

  • Actually, the following code is working:

    class ConfigManager {
       Locale loc;
       static ConfigManager _instance;
       factory ConfigManager() => _instance ??= new ConfigManager._();
    
       void init(Locale loc) {
          this.loc = loc;
       }
    
       ConfigManager._();
    }
    

    With the init method i can assign the needed stuff to my Singleton ConfigManager in order to get what i need on-the-fly later. However I'll do more research in terms of more performance and code elegance (maybe with different patterns).