In this article, we are going to learn about the StatefulBuilder widget in flutter and will also learn when and where to use this widget.
StatefulBuilder is a widget having a mutable state (whose state can be changed). What makes it’s special is that it only rebuilds the particular widget that is wrapped under the Stateful Builder.
Check our Flutter app development services page.
This widget provides a state setter method that is responsible for the rebuilding of the widget.
KEEP IN MIND
The widgets that you want to update should be kept inside this widget.
For example:
The Below code will not work, i.e the text in the Text widget will not update because it needs to be wrapped in this widget.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
int count = 0; @override Widget build(BuildContext context) { ... Column( children: <Widget>[ StatefulBuilder(builder: (context, setState) { return ElevatedButton( onPressed: () { setState(() { count++; }); }, child: Text("Add")); }), Text("$count") ], ), ... } |
What you need to do here is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
int count = 0; @override Widget build(BuildContext context) { ... StatefulBuilder(builder: (context, setState) { return Column( children: <Widget>[ ElevatedButton( onPressed: () { setState(() { count++; }); }, child: Text("Add"), ), Text("$count") ], ); }) ... } |
Now the above code will work perfectly.
Can we replace stateful widget with statefulbuilder widget?
We cannot replace the stateful widget with this widget because Flutter only preserves associated states that we provide in stateful widgets.
1 2 3 4 5 6 7 |
... @override State<HomePage> createState() => _HomePageState(); ... class _HomePageState extends State<HomePage> { ... |
If we use a stateful builder widget and store any state in instance variables in the stateless widget it may be lost at any time as the constructor for the stateless widget may be called multiple times, just like the build method.
Conclusion
Now we know how to use the stateful builder widget in flutter. We also know why we cannot replace the stateful widget with this widget.
To read more blogs on flutter head over here.
Reference: Can Stateful Builder Step into the shoes of Stateful Widget?