1

I have a simple question. In Flutter docs it is explained build method can be called many times by framework and it is recomended that we should only return widgets through the build method. But even we return only widgets, isn't it causing some performance issues? If build method is called 20 times in a second, does not it mean widgets will be rendered 20 times and should not it be slow? If Flutter framework optimizes rendering widgets, how?

Can you please reference some detailed docs or answers for that?

shuster
  • 184
  • 3
  • 10

3 Answers3

1

This is a really good question. The Flutter team has put together this really useful video on YouTube that explains this perfectly and in details. Essentially you need to understand the difference between the Widget tree and the element tree. Every widget inside your widget tree is backed by something called an element, and this element is what Flutter actually uses to draw "things" on the screen. The widgets are the visual representation of the elements from the programmer's perspective while the elements are the actual visual representation of the widgets on the screen. The optimizations are done at the element tree level which you usually don't get to work with directly.

1

Check out that video, there is a lot of useful information here

Kirill
  • 108
  • 4
1

Here is the explanation about how Flutter handles render optimization thanks to the suggested videos and Flutter docs.

Flutter does not only have widget trees. For each visual representation on UI there is actually 3 main trees which are Widget Tree, Element Tree and Render Objects.

Widget Tree is hierarchy of widgets and includes all the widgets created. But since widgets are immutable and changed in the tree over time, there should be another tree called Element Tree which keeps the states and optimizes widget rendering.

Element Tree is the tree which Flutter uses to render widgets on the screen and is not changed a lot over time same as Widget Tree because whenever a widget is changed in the Widget Tree, if the new widget has the same type as before, element tree keeps the element for the corresponding widget. For example if you only change a Text widget's text in the widget tree, Widget Tree is going to be changed but Element Tree is going to stay same because Text widget still has the same runtimeType as before.

So that render optimization is mostly about reusability. Flutter framework is trying to reuse the objects as much as it can. Even the Widget Tree is changed a lot over time, Element Tree is not changed a lot same as the Widget Tree and use the same element object if the widget type is not changed.

shuster
  • 184
  • 3
  • 10