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

[Dart 3.0] GetIt can't detect T type properly #331

Open subzero911 opened 1 year ago

subzero911 commented 1 year ago

After the latest Flutter upgrade, registerSingleton inside of VoidCallback is not working anymore:

image

It worked before Dart 3.0. Now they probably have stricter type checking. In runtime it crashes with the following error image

The bug disappears when I explicitly indicate the type: image

This bug appears in VoidCallback only, not in a plain code. It also can be fixed if I used: () {} instead of () =>

image

The reason behind: a generic by default takes the root return type (void), and Dart tries to put void into T extends Object constraint, and this apparently causes this assert to be falsely posivite: image

Any ideas on it?

escamoteur commented 1 year ago

@subzero911 your analysis seems correct, although I don't think that this can be fixed by GetIt. I always recommend passing the Generic type explicitly because then there is no room for doubt

@mraleph @munificent this comes sort of surprising, is that the intended consequence?

subzero911 commented 1 year ago

First of all, it's strange that we can do call GetIt.instance(). Is it a callable class? I personally never did it. Do we actually need this assertion?

escamoteur commented 1 year ago

Actually the assertion isn't about calling it this way, but if people call GetIt.instance() accidentially you get this type of eception too. And yes GetIt is a callable class from the beginning. I most of the time to something like this in my setup file:

final di = GetIt.instance;
// and then use it like
di<Mytype>().myMethod();
subzero911 commented 1 year ago

I always recommend passing the Generic type explicitly because then there is no room for doubt

But writing GetIt.I.registerSingleton<MyControllerWithVeryLongName>(MyControllerWithVeryLongName()) every time is not concise.

escamoteur commented 1 year ago

That is true, but you don't register that many types and in my case I often register an abstract interface class with a selected implementation then I have to provide the type anyway Am 29. Mai 2023, 11:21 +0200 schrieb Sergey Molchanovsky @.***>:

I always recommend passing the Generic type explicitly because then there is no room for doubt But writing GetIt.I.registerSingleton(MyControllerWithVeryLongName()) every time is not concise. — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.Message ID: @.***>

munificent commented 1 year ago

I'm not sure why this behavior is different in Dart 3.0. @stereotype441 or @eernst might know more.