Diving into Flutter Widget (P1)

Kim Quy
3 min readMay 12, 2021

--

How build & paint on screen?

To answer this question, we have to know about widget trees, element trees, and render trees inside Flutter.

Widget Tree, Element Tree, Render Tree.

What you work with is a widget tree. But actually, when you run an app, Flutter will create a widget tree, element tree, and render tree.

Widget Tree — Element Tree — Render Tree

Widget Tree

  • Widget tree for configuration, created by your code. It rebuilds frequently.
  • Widget tree is constantly changing basically whenever you call setState.
  • Whenever the build methods get executed, Flutter rebuilds that widget tree, whilst that happens relatively often.

Element Tree

  • Element Tree created by Flutter automatically base on widget tree.
  • It links widgets with rendered objects. It rarely rebuilds.
  • Element Tree does not rebuild with every call to the build method.
  • The element has a reference at the widget which holds all the configuration for that element and then it also holds a reference to the state object.
  • The state object is managed independently of the widget.

Render Tree

  • Render Tree rendered objects on the screen. It rarely rebuilds.
  • Render Tree is the end. It is the representation of what really ends up on the screen.
  • Render Object is a node of the render tree. It is the source for drawing UI.
When you use Dart DevTools, every Widget Object will have a renderObject inside.

How does Flutter build & paint on screen?

Stateless: The content in a stateless widget cannot change. So your configuration only runs build() and displays content on the screen.

Stateful:

  • The build() method runs, It will create new instances of all widget classes.
  • It will create an Element in the Element tree and create a state object also.
  • The state object holds logic and the internal state of Widget and it is owned by Element, not the Widget. So, If you change the widget. It will not affect the screen. That is the reason why we need setState().
  • setState() is update State Object and automatically leads to build() being called. But, it will not create a new Element or state object.
  • Calling setState() marks and therefore the element in the element tree that belongs to the widget is dirty.
  • Flutter aims to give a 60fps application.
  • So as something changed here and for the next refresh (1 of 60 fps). Flutter will then take the new configuration and update the screen.

Rebuilding the widget tree is a core mechanism of Flutter and really not bad.

Flutter manages this efficiently to not rebuild the element and the render tree all the time.

References:

--

--

No responses yet