Search code examples
flutterblocflutter-bloc

MultiBlocProvider's misusing cases


We know that, we need to put BlocProvider instance on top of widget tree's part, which we want to get access data inside this part of tree. What if we use all BlocProvider instance on top of whole tree, even most of them are only necessary for some small bottom parts of tree. Is it considered as mistake, because of we are passing data across whole tree(despite it is unnecessary) every time we call it, or there will be zero performance differences between putting all blocProvider on top and putting BlocProviders only on appropriate tree parts.


Solution

  • It is considered bad practice to put everything at the top of the tree for several reasons. It breaks several common good programming practices, SOLID amongst others. You e.g. don't have all your variables and class instances in your applications as global variables.

    And when it comes to performance, yes it can have a negative effect on performance. If and how much is of course not possible to say before hand because it depends on how many, what the blocs do, how they are used and etc.

    Some should obviously be at the top, so they should be. But not all. So provide them only where they are needed as it will be better performance wise and will keep your code cleaner.

    Edit:

    This is from the creator (Felix Angelov) of flutter bloc:

    The main disadvantages of providing all blocs globally are:

    • The blocs are never closed so they are consuming resources even if they aren't being used by the current widget tree
    • The blocs can be accessed from anywhere even if the state of the bloc is scoped to just a particular feature
    • The blocs typically end up needing some sort of "reset" event to revert back to the initial state which is not necessary if they are properly scoped and automatically disposed by BlocProvider

    My recommendation is to create a bloc per feature and provide that bloc only to the specific subtree that needs it. Hope that helps 👍