1

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.

docdev
  • 943
  • 1
  • 7
  • 17

2 Answers2

2

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).

docdev
  • 943
  • 1
  • 7
  • 17
0

how about use const constructor? below is how flutter does it.

// full source code in /sky_engine/lib/ui/painting.dart
class Colors {

     const Color(int value) : value = value & 0xFFFFFFFF;

     static const Color white = Color(0xFFFFFFFF);

} 

then use it by calling Colors.white

class YourApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            title: 'your app',
            theme: ThemeData(
                primaryColor: Colors.white,
            ),
        );
    }
}
linxie
  • 1,849
  • 15
  • 20
  • Thank you for your answer ! In my opinion this will be something javascript-like stuff. However i'm trying to make a comparison between different approaches and relative performance/code elegance. – docdev Jun 10 '20 at 15:04