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

Get with type #298

Closed lacopiroty closed 1 year ago

lacopiroty commented 2 years ago

Hi! :)

Is it possible to add support for type parameter to "get/call" etc. functions? I also created a PR :)

example for get function:

Current implementation:

T get<T extends Object>({
    String? instanceName,
    dynamic param1,
    dynamic param2,
  }) {
    final instanceFactory = _findFactoryByNameAndType<T>(instanceName);
    // normal implementation of GetIt
}

Expected implementation:

T get<T extends Object>({
    String? instanceName,
    dynamic param1,
    dynamic param2,
    Type? type,
  }) {
    final instanceFactory = _findFactoryByNameAndType<T>(instanceName, type);
    // normal implementation of GetIt
}
shtse8 commented 1 year ago

I have the same question, how can we resolve instance by runtime type?

wim07101993 commented 1 year ago

This issue has been open for about 6 months, could someone please take a look at the pr? :)

escamoteur commented 1 year ago

@esDotDev @dancamdev what are your thoughts on this? get_it used the generics from the beginning and I'm somewhat hesitant to add a type, although internally I do use is too.

esDotDev commented 1 year ago

I'm not clear on the use cases, but if there are valid ones then I don't see how it would hurt to allow an optional type.

escamoteur commented 1 year ago

Some people want to access objects at runtime with a variable type

escamoteur commented 1 year ago

One question I have is, how can this be done in a typesafe way? I mean how can the analyzer control if the destination variable has the correct type?

escamoteur commented 1 year ago

included in V7.6.0

escamoteur commented 7 months ago

I just stumbled again upon these lines

    assert(
        type == null || type is T,
        'The type you passed is not a $T. This can happen '
        'if the receiving variable is of the wrong type, or you passed a gerenic type and a type parameter');

and I really wonder how any of you uses the option of passing a runtime type to get an object from get_it as it turns out this check will always fail if the receiving variable is defined with any other type than Object due to the limitation and also my misunderstanding of what the is operator it capable of see https://github.com/dart-lang/sdk/issues/43390#issuecomment-2014863486

You should all have gotten a lot of assertion errors from that. I now fixed that so that the check is done correctly