flutterdartinjectable

Singleton injection with parameter


I do want to use the packages get_it and injectable. They are both wonderful, but I'm facing a issue. Maybe my idea is wrong.

My application has two singletons and I want to use different base urls for different app flavors. So I added a parameter to the singleton constructor with the baseUrl value.

The problem is now, that injectable has only @factoryParam as annotation. The name shows the problem. It's not for singletons.

What will be the best practice for that issue? Should I get rid of constructor injection and inject the baseUrl within the singleton like

var url = get_it.get<Config>();

or is that not the best idea?


Solution

  • It can be achievied in few ways, you can register different strings for different env e.g.

    @Environment("dev")
    @Named("url") // in case if you injecting other strings
    String get devUrl...
    
    @Environment("stage")
    @Named("url") // in case if you injecting other strings
    String get stageUrl...
    

    [Update with example]

    @Environment("dev")
    @injectable
    class ExampleOne{
    final String _url;
    
    ExampleOne(@Named("url") this._url)
    }
    
    @Environment("stage")
    @injectable
    class ExampleTwo{
    final String _url;
    
    ExampleTwo(@Named("url") this._url);
    }
    

    or just one class:

    @injectable
    class Example{
    final String _url;
    Example(@Named("url") this._url);
    }