fluttercommunity / get_it

Get It - Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your App. Maintainer: @escamoteur
https://pub.dev/packages/get_it
MIT License
1.36k stars 149 forks source link

Error Null check operator used on a null value in get_it library #312

Closed nahimilega closed 1 year ago

nahimilega commented 1 year ago

Hi while calling the get method

getIt.get<InstructionUIController>().showCongratulationsScreenAfterInstruction(); We are getting the error:

Null check operator used on a null value. Error thrown null.
       at _GetItImplementation._findFactoryByNameAndType(get_it_impl.dart:380)
       at _GetItImplementation.get(get_it_impl.dart:393)
       at MainController.instructionsComplete(MainController.dart:238)

The fun thing is it happens rarely, we even were not able to find this in testing... but it is coming up for some users in production.

InstructionUIController is registered beforehand. getIt.registerSingleton<InstructionUIController>(InstructionUIController()); Could you please us figure out what could be the potential reasons for this?

Version
get_it: ^7.2.0

PS: I guess this is similar to the issue https://github.com/fluttercommunity/get_it/issues/283

nahimilega commented 1 year ago

@escamoteur did you got time to look into this issue

escamoteur commented 1 year ago

Sorry for the late response. The piece of code in question is:

_ServiceFactory _findFactoryByNameAndType<T extends Object>(
    String? instanceName, [
    Type? type,
  ]) {
    final instanceFactory =
        _findFirstFactoryByNameAndTypeOrNull<T>(instanceName, type: type);

    assert(
      instanceFactory != null,
      // ignore: missing_whitespace_between_adjacent_strings
      'Object/factory with ${instanceName != null ? 'with name $instanceName and ' : ''}'
      'type $T is not registered inside GetIt. '
      '\n(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;'
      '\nDid you forget to register it?)',
    );

    return instanceFactory!;
  }

As you can see the only ! is at the return value. I change the assert to a throwIf so that you can get a meaningful exception when that happens. If that happens it means that somehow the object you requested was never registered or removed.

escamoteur commented 1 year ago

just pushed 7.4.1 to pub