How does setState() rebuild child widgets?
When the widget tree rebuilds, Flutter compares using ==
the previous and new widget returned by the build
method.
There are two scenarios in that situation:
==
isfalse
. In that case, Flutter will compare theruntimeType
&key
to know if the state of the previous widget should be preserved. Then Flutter callsbuild
on that widget==
istrue
. In which case, Flutter aborts the building of the widget tree (aka won't callbuild
).
This is an optimization possible thanks to the immutability of widgets.
Since widgets are immutable, if ==
haven't changed then it means that there's nothing to update. Flutter can therefore safely optimize that.
When you use setState(())
only the build()
will get called. Now in this method you are again invoking StatefulChild()
(first line) which further instantiates this class so the build()
method of this class gets executed.
But when you use statefulChild
it is not creating a new instance because
StatefulChild statefulChild = StatefulChild();
is used outside the build()
method. So it just got called once.