As the title states, you don’t always need a StatefulWidget
.
When developing Flutter applications, depending on the widget you are working on, the build method could be quite large. Using a StatefulWidget
means rebuilding the entire widget tree every time setState
is called.
A more nuanced way of handling state changes would be to use StatefulBuilder
.
Stateful Builder
StatefulBuilder
is a widget provided by Flutter which allows you to inline state in your build method. This widget is actually a type of builder which uses StatefulWidgetBuilder
. This function has two parameters, context
and setState
. The first parameter context
is the BuildContext
or the elements. The second and more interesting parameter is setState
.
Looking at the source of StatefulWidgetBuilder
, we can see that setState
is a StateSetter
. StateSetter
is a callback to State.setState
. When called, this method rebuilds the widget tree with the updated changes.
How to use Stateful Builder
Now that you have been introduced to StatefulBuilder
, you may be wondering how it is used.
StatefulBuilder
is best used in situations where you have a medium/large widget tree and state needs to be introduced for a small subsection of that tree.
The above code snippet shows StatefulBuilder
being used in a Card
. Instead of making the entire card stateful, we are using StatefulBuilder
to build the section of the tree where state is needed. In this case, we are using it to only build the Row
of buttons and text. As a result of this, when onPressed
is triggered and setState
is called, only the Row
and its children are rebuilt, all other widgets are not.
If the entire widget was made stateful, instead of having only the Row
rebuilt, the entire Card
would have been rebuilt.
Video of finished app:
Conclusion
StatefulBuilder
like many other obscure Flutter widgets provides great functionality and helps to better improve performance. It gives you fine grain control of which parts of the widget tree you are rebuilding and when.
I hoped you enjoyed this article, if you have any questions or spot any errors or have a suggestion for an article, please leave a comment or reach out to me on Twitter, I am @Nash0x7E2. The full source code for this project can be found on my GitHub: https://github.com/Nash0x7E2/stateful-builder. Also be sure to follow Flutter Community to keep up with everything as they relate to Flutter.
— Nash