Flutter BuildContext

I’ve just finished reading A pragmatic guide to BuildContext in Flutter, and these are my take aways.

Also, read the article, it goes into more depth, and explains things better than I will here.

Widget Tree vs Element Tree

As developers it’s easy to focus only on building the widget tree - creating a hierarchy of nested widgets that build the required UI.

Flutter, on the other hand, is more concerned with the element tree than the widget tree.

For example, pressing the button in the example counter app replaces the Text('0') widget in the Widget tree with a new Text('1') widget, leaving the previous to be garbage collected. In the Element tree, however, the element’s .widget field is merely updated to refer to the new widget.

Context Issues

We can take some steps to reduce, and remedy build context issues:

  • Prefer many small widgets over one with a large build method. This reduces code complexity, increases testability, and reduces the size of rebuilds, increasing performance and reducing jank.
  • Check context.mounted before accessing context.of(...) etc.
  • Use the Builder(...) widget
  • Use a GlobalKey, which the Flutter documentation refers to as a “less elegant but more expedient solution”.

Leave a comment