Skip to content

blocbuilders as low as possible

chonghorizons edited this page Dec 23, 2021 · 2 revisions

Stub, needs filling out. Hit Edit to fill out.

The Practice

BlocBuilders as low as possible

Rationale

Put your BlocBuilders(https://pub.dev/documentation/flutter_bloc/latest/flutter_bloc/BlocBuilder-class.html) as low as possible in the widget tree to have efficient code.

You could have a BlocBuilder that has lots of widgets


This is too high:

  • Home with BlocProvider above
    • BlocBuilder<BlocA,BlocAState>
      • Scaffold
        • AppBar
        • BottomNavigationBar
        • Column
          • Header
          • Stuff1
          • Stuff2 // This is where your BlocAState is used.

This puts BlocBuilder as low as possible

  • Home with BlocProvider above
    • Scaffold
      • AppBar
      • BottomNavigationBar
      • Column
        • Header
        • Stuff1
        • BlocBuilder<BlocA,BlocAState>
          • Stuff2 // This is where your BlocAState is used.

Examples

See the widget tree here and the overall flutter_todos example. https://github.com/felangel/bloc/blob/593693be6021e35ec1df5cc59cb9381a206f5e84/docs/fluttertodostutorial.md#widget-tree

Advantages

  • If your BlocBuilder is too high you might have unnecessary rebuilds. In the example above, the whole scaffold could rebuild.
  • Lower is more efficient

Tip: You can use multiple BlocBuilders if you need to use the BlocState multiple times and in multiple cases. See the example.

Disadvantages

  • None.
    • In some cases, you might be tempted to put your blocBuilder high up because it's needed in multiple places. Just use multiple BlocBuilders: i.e. one BlocBuilder every place you need it.

  • Home with BlocProvider above
    • BlocBuilder<BlocA,BlocAState>
      • Scaffold
        • AppBar
        • BottomNavigationBar
          • Counter // This is first place where your BlocAState is used.
        • Column
          • Header
          • Stuff1
          • Stuff2 // This is the second place where your BlocAState is used.

This puts BlocBuilder as low as possible and uses two BlocBuilders

  • Home with BlocProvider above
    • Scaffold
      • AppBar
      • BottomNavigationBar
        • BlocBuilder<BlocA,BlocAState>
          • Counter // This is first place where your BlocAState is used.
      • Column
        • Header
        • Stuff1
        • BlocBuilder<BlocA,BlocAState>
          • Stuff2 // This is where your BlocAState is used.

Note: The Scaffold won't need to rebuild. Also, the AppBar, Column, Header, and Stuff1 will not rebuild either. If there is any expensive operation associated with any of these things, this can make a big difference.

Votes

  • @chonghorizons recommends this 100% of the time. (Is unaware of any situation where having BlocBuilder higher is advantageous).

Related

BlocProvider-placed-as-low-as-possible

Clone this wiki locally