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?
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.
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.
The documentation lists all specific cases when rebuilds can occur:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With