Is it possible to provide a null implementation when registering something on Flutter's GetIt?

63 Views Asked by At

Given we use third-party packages, one of them expects to receive a null in the production code and a custom implementation in the test code. So, it'll be convenient to have a GetIt provider that gives us null on production while an actual tailored implementation on tests.

We tried getIt.registerSingleton<OurOwnInterface?>(()=>null); but it doesn't even compile. And the documentation doesn't specify if that's possible or not.

1

There are 1 best solutions below

5
On BEST ANSWER

One thing you could do is wrap it with a try catch:

OurOwnInterface? _getOurOwnInterface() {
  try {
    return GetIt.I.get<OurOwnInterface>();
  } on StateError catch (_) {
    return null;
  }
}

The complete gist is here

Edit:

extension GetItExtension on GetIt {
  T? getOrNull<T extends Object>() {
    try {
      return GetIt.I.get<T>();
    } on StateError catch (_) {
      return null;
    }
  }
}

//and then use like:
OurOwnInterface? appModel = GetIt.I.getOrNull();