Rebuilding a portion of code using StatefulBuilder Widget

Hello dev, sometimes you need to rebuild a widget according to the user input or action, but if you are using setState to trigger this action in code, you may face the problem to rebuild the entire widget tree, and doing it can cost a lot of memory so it can make the app lag.

In this article let’s talk about a widget that can save you from this in certain occasions, so bear in mind that you can use this approach but not every time so be cautious.

Using the counter app, I’m going to modify the implementation just to keep things clear, and instead to have the click action to increment the counter using the FloatingActionButton, I’ll just put the function in a GestureDetector which is going to wrap the text number.

For now all the widget is being rebuilt every time I execute the tap, so let’s add another widget to archive the rebuild only the text widget.

Let’s wrap the GestureDetector with a StatefulBuilder, and now we have an own setState function that I called textSetState which is going to trigger the update only for the text counter.

Now if we use the print function to see where the code is being executed, we can see that is only going through the StatefulBuilder.

Now when thinking about rebuilding something, try to see if this solution fits somehow, in order to optimize your app a little more.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store