flutterdependency-injectionflutter-cubit

Flutter(Cubit and Repository) - Where to inject dependencies


I'm relatively new to Flutter and Cubit pattern and I'm trying to figure out which are the best ways to work with them. Recently my colleague and I have been struggling to reach an agreement where we should inject the cubit and the repositories.

Reading the bloc/cubit documentation, it is not very clear about where we should do it.

IMO, everything that we need to instantiate, should be injected as high in the tree as possible where two different components that will use this information have in common.

For my colleague, each widget can instantiate one cubit, meaning that each widget will have its own instance of the cubit.

I would like to discuss about what are the community thoughts and best practices regarding the dependency injection and architecture regarding cubit.


Solution

  • There is no single answer to that question. It all depends on your project structure and architecture. In general though:


    IMO, everything that we need to instantiate, should be injected as high in the tree as possible where two different components that will use this information have in common.

    This is a good approach. Most frequently it will be above your routes, so somewhere above your MaterialApp. If you make use of nested Navigators, then this common place could be above this nested Navigator.

    On a more technical side, how will you manage the dependencies used in those cubits/blocs is up to you and your liking. I find some of the options:

    The most correct choice will be something that you (and your colleagues) are most comfortable developing with and that scales well.