skip to Main Content

I’m using this singleton in my app:

import 'package:injectable/injectable.dart';

@singleton
final class TMDB {
  ...
}

In several parts of my app I use statements similar to this:

import '../../../config/initializers/di.dart';
import '../../../config/servers/tmdb.dart';

...
final myUrl = getIt<TMDB>().baseURL;
...

As you can see I have two import statements and getIt<TMDB>() may be used several times in my app, then I thought I could use a variable declared in di.dart:

import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';

import 'di.config.dart';

final getIt = GetIt.instance;  
  
@InjectableInit()  
void configureDependencies() => getIt.init();

final tmdb = getIt<TMDB>();

This would simplify the previous statements, but if tmdb represents a singleton and is a global variable (getIt is too) so what’s the point of using get_it/injectable if I can directly declare my singletons as the usual way?

I cannot see the real benefits of using get_it/injectable or similar tools.

3

Answers


  1. get_it is more than a singleton. It’s also a service locator, useful during testing to mock the "real" singletons. It’s also written/tested/debugged/documented code, rather than using your own homegrown singletons.

    Login or Signup to reply.
  2. hello do you like this website Its so nice

    Login or Signup to reply.
  3. It depends but mainly, get_it provides a flexible way to perform dependency injection, while injectable builds on top of it, adding code generation and other features to enhance productivity and maintainability in larger projects.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search