Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often is the build method called?

Tags:

flutter

dart

I noticed that the build method gets called often in a flutter app.

I know that if the states of the page change in a statefulWidget, the build method gets triggered. But I also noticed that the build method is called even if nothing is changed in the app.

Considering the case where you leave the app to itself, is it normal for the build method to get called frequently? If so, why and how often?

like image 595
Vahid Zadeh Avatar asked Mar 04 '23 13:03

Vahid Zadeh


1 Answers

Why

The build method is called any time you call setState, your widget's dependencies update, or any of the parent widgets are rebuilt (when setState is called inside of those).

Your widget will depend on any InheritedWidget you use, e.g. Theme.of(context), MediaQuery.of(context) etc.
This means that if the theme changes for example or the screen orientation swaps, your widget will also be rebuilt.

When you use widgets like MaterialApp, Scaffold etc. that are provided by the framework, your widget will be rebuilt a lot because these parent widgets depend on many InheritedWidget's and then are rebuilt, which causes your widget to be rebuilt as well.

How often

There is no number for how many rebuilds are "normal" as this completely depends on your tree size and most importantly widgets are in that tree. If you were to run runApp(Container()), there would be no rebuilds.

Just keep in mind that all of these rebuilds probably have a good reason to occur and Flutter is built for this, so you do not need to worry about this.

The only point you should start worrying is when you have constant rebuilds that are probably caused by some builder (which calls setState internally) you are using incorrectly.

Exactly when

The documentation lists all specific cases when rebuilds can occur:

  • After calling initState.
  • After calling didUpdateWidget.
  • After receiving a call to setState.
  • After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes).
  • After calling deactivate and then reinserting the State object into the tree at another location.

Rebuilds from parent widgets

If you want to understand how InheritedWidget works, see this answer. It also touches when a rebuild in a parent widget causes the subtree to rebuild.

like image 149
creativecreatorormaybenot Avatar answered Mar 27 '23 16:03

creativecreatorormaybenot