My Notes on Using the StatefulBuilder Widget
In this blog post, I'll be sharing my notes on using the StatefulBuilder, which I discovered while playing around with the widget.
A few days ago, one of my friends shared a widget in a post that I wasn't familiar with, but it seemed useful. So, I started exploring the StatefulBuilder widget.
In this blog post, I'll be sharing my notes on using the StatefulBuilder, which I discovered while playing around with the widget.
If you're not familiar with the StatefulBuilder widget, I recommend watching the official "Widget of the Week” video before reading further.
1. It Doesn’t Replace StatefulWidget
If you look at the example from the video, you'll see that we have a mutable state variable called isExpanded, which still needs a StatefulWidget to hold that state.
We can check this in the official DartPad example:
The lerp variable is updated in the setState method of the StatefulBuilder, but the state is saved under the _MyWidgetState, which is a StatefulWidget. In the above case, we can easily replace StatefulBuilder with ValueListenableBuilder.
2. Under the Hood: It's Just Another StatefulWidget
If we use StatefulBuilder in the widget tree, it's essentially the same as having one StatefulWidget wrapped inside another StatefulWidget. Having a separate StatefulWidget allows Flutter to track its state independently, which is why we're able to update the InexpensiveWidget without rebuilding the ExpensiveWidget.
3. Using a Different Name for setState for StatufulBuilder
In regards to point 1, it's likely that the StatefulBuilder will be inside a StatefulWidget. To avoid confusion on which setState() we're calling inside the StatefulBuilder, consider changing the name of setState to setBuilderState. This will also allow us to update the setState method for the parent widget.
Let’s say we want to rebuild the ExpensiveWidget when the lerp is 0.5. In this case, we can use setState from the parent StatefulWidget:
You can find the updated version of the above dartpad here.
4. Beware of closure changes
I’ve revised the dialog example from the official document to explain my point here.
An interesting observation to note would be that if the value of the count were to change before it reaches the end of its scope then the value remembered by the Closure would also change.
In the example above, when we open the dialog, both the "Inside Increment " and "Outside Increment" values are initially zero. However, if we click the "Inside" button after clicking the "Outside" button 6 times, the count in “Inside” will start at 7.
That’s it for now.
Check the updated Dartpad here.
If you found this post helpful or informative, would you consider sharing it with your friends and colleagues? It would mean a lot to me, and I believe it could be valuable to them as well.
Thanks for reading!