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