Provider vs. Get_it

前端 未结 3 1121
醉酒成梦
醉酒成梦 2021-02-07 01:56

Searching for Dependency Injection solutions for Flutter, I found two awesome libraries: provider and get_it.

As far as I can see, provid

相关标签:
3条回答
  • 2021-02-07 02:38

    The main difference between both is that provider is not strictly dependency injection.

    By using widgets, provider is also able to:

    • providers are compatible with the Flutter devtool
    • know when a variable cannot be accessed (scoped to a tree)
    • know when to create and dispose of an object
    • synchronize model -> model and model -> UI
    • override some values for only a specific widget tree
    • voluntarily prevent circular dependency

    All of these are, while optional, good for the health of your app in the long run.

    It ensures that you're always up to date, makes it harder to have "spaghetti code", and makes your different elements more composable.

    0 讨论(0)
  • 2021-02-07 02:50

    I am explaining just one limitation which I practically found, there may be others too.

    After searching many tutorials and topics on Get_it that why people use Get_it() even we have dependency injection in the provider, I was unable to understand the difference in terms of DI. Then I stuck in a Scenario and find the answer to your question that "what are the limitations".

    Are there any more differences and limitations between them?.

    Scenario:

    I had Nested widgets, Widget A has Widget B and Widget B has Widget C, I was using the provider and was accessing values in each widget whenever value changed. It was great, Then I make a new widget D which was a separate widget, it was not inside the widget A hierarchy. But when I try to access the same value in Widget D it was not changing. Because widget D is not in the tree of Widget A. Now here comes the limitation of dependency injection of the provider.

    Conclusion

    You will use Get_it to access values out of the tree widget. But you can't access the updated value using provider

    Note

    you need to wrap the app with the provider to access all dependencies.

    0 讨论(0)
  • 2021-02-07 02:54

    Get It is not a dependency injection solution but a service locator.

    It's useful if you want to rapidly switch between two or more implementations of a class. For example to mockup a service, and change between the "real" service or the fake one (for debugging purpose).

    Indeed it can't retrieve/supply reference to an existing object (exception is for singleton, but you can do the same by yourself without much more effort) and can supply only new objects.

    0 讨论(0)
提交回复
热议问题