I just need some idea on how flutter stateful widgets build their stateful children when setState() is invoked. Please look at the code below.
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.
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:
==
is false
. In that case, Flutter will compare the runtimeType
& key
to know if the state of the previous widget should be preserved. Then Flutter calls build
on that widget
==
is true
. In which case, Flutter aborts the building of the widget tree (aka won't call build
).
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.