Flutter provides the setState() method as a method to change the state of any given widget, but sometimes you may wish to update just a specific widget and not rebuild the whole tree. That is where StatefulBuilder comes into play - with it, you can update just one specific widget without rebuilding its entire tree!
In this article, we will cover how to refresh a specific widget using setState and StatefulBuilder in Flutter.
StatefulBuilder is a Flutter widget that allows you to create widgets with their own mutable state, similar to StatefulWidget but differing in that its setState() method allows only its widget to update.
StatefulBuilder makes using StatefulBuilders easier. Simply wrap your widget with it, and provide a callback function that will be called when its state needs updating. The callback function takes two arguments; they are: BuildContext and StateSetter - these represent the context in which your widget resides wrapped by StatefulBuilders; while StateSetter acts as a way of updating its state directly.
If you want to refresh a specific widget, wrap its instance with StatefulBuilder and call its StateSetter function for update of state. Here is an example:
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {return Column(children: [Text('Counter: $counter'),RaisedButton(child: Text('Increment'),onPressed: () {setState(() {counter++;});},),],);},)
In this example, we use a Column widget which houses a Text widget displaying a counter value and an IncrementButton that increments it upon press. All three components are wrapped by StatefulBuilder for ease of use.
When the RaisedButton is pressed, its onPressed callback function will be triggered and we use its setState() method of the StateSetter to change its counter value accordingly. This causes both Text and Column widgets to redraw themselves with their new counter values but not Text widget.
Flutter’s StatefulBuilder widget offers you the flexibility of updating a specific widget’s state without rebuilding its entire tree, which can come in handy when updating only part of your UI and not all at once.
We hope this article has been beneficial in explaining how to refresh a widget using setState and StatefulBuilder in Flutter. If you have any queries or comments below, feel free to submit them below.
LESSONS
COURSES
TUTORS
Quick Links
Legal Stuff
Social Media