Difference between using getit and declaring your own instances

Viewed 328

I am trying to understand the best practices in Dart and I saw in couple of instances that people declare singletons without the getit package and also the factory declarations are also a bit confusing for me. So let's assume I have these two classes below:

class Singleton {
  static final Singleton _singleton = Singleton._internal();

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}


class RegularClass {
  RegularClass();
}

I have two questions here:

  1. What is the difference between Singleton() and GetIt.I.registerSingleton<RegularClass>(() => RegularClass());

  2. What is the difference between RegularClass() and GetIt.I.registerFactory<RegularClass>(() => RegularClass());

If these cases don't really matter, then what cases matter? What are the different use cases for these?

1 Answers

There is no real difference.

But as your app grows, using getIt (especially together with e.g. injectable) will make your app a lot easier to work with and save you a lot of time.

Edit (in response to requested elaboration):

As an example. Consider having a class setup as below, that use an API which you have setup as an interface (abstract class)

@Injectable
class MyClass {
  MyClass(this.myApi);
  final IApi myApi;
  ...
}

@LazySingleton(as: IApi)
class MyApi implements IApi {
  ...
}

You will then be able to let getIt and injectable solve these dependencies, factories and singletons where needed and appropriate, so that when you want to use e.g. MyClass, you don't have to consider what needs to be injected where, and what type of parameters that needs to be injected where.. All you have to call is:

final instaceOfMyClass = getIt<MyClass>();

And on top of this, if you want to have e.g. a Mock implementation of IApi, or a separate implementation for production and some test environment, you can define that with the annotations, so that your entire setup is handled based on one single input parameter when you launch your app. So, instead of what I wrote above for the singleton, you could as an example do two separate implementations of the API, and let getIt solve everything for you based on your environment. Meaning you can still just call getIt<MyClass>() to get MyClass, but your instance of IApi will differ based on your setup:

@LazySingleton(as: IApi, env: ['dev'])
class MyTestEnviromentApi implements IApi { ... }

@LazySingleton(as: IApi, env: ['prod'])
class MyProductionEnvironementApi implements IApi { ... }
Related