Skip to content

Instantly share code, notes, and snippets.

@Nash0x7E2
Created October 22, 2018 23:54
Show Gist options
  • Save Nash0x7E2/ac29695ca5b199350e7c7b53dc6a2d77 to your computer and use it in GitHub Desktop.
Save Nash0x7E2/ac29695ca5b199350e7c7b53dc6a2d77 to your computer and use it in GitHub Desktop.

You don't always need Stateful Widgets: Stateful Builder


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 everytime setState is called.

A more nuanced way of handling state changes in a large build method would be to use StatefulBuilder.

Stateful Builder

StatefulBuilder is a widget provided by Flutter which allows you introduce state at a localized, contained point in your build method. This widget is actually a type of builder which uses StatefulWidgetBuilder. This builder has two parameters, context and setState. The first parameter context is the BuildContext or the elements. The second and more interesting parameter is setState.

https://gist.github.com/00e2e85a937f9f62e4fd63b5230a611c

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.

https://gist.github.com/52f415f9946c69ea645fea4b98f3a7cb

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. 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

Stateful Builder like many other obscure Flutter widgets provide adds great functionality and helps to better improve performance.

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: (TODO). Also be sure to follow Flutter Community to keep up with everything as they relate to Flutter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment