Stateful Widgets
Tapping "Watered" on the fern should tick it off and update the count on screen. That widget must remember something between frames and redraw when it changes. Stateless widgets cannot do that; stateful widgets are built for it.
The rule
Change the value inside
setState, and Flutter runsbuildagain.
A stateful widget is two classes:
class WaterCounter extends StatefulWidget {
const WaterCounter({super.key, required this.plant});
final String plant;
@override
State<WaterCounter> createState() => _WaterCounterState();
}
class _WaterCounterState extends State<WaterCounter> {
int count = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => count++),
child: Text('${widget.plant}: watered $count times'),
);
}
}- The widget class is immutable, like any widget. It holds the inputs, here
plant. - The State class is created once by
createStateand lives as long as the widget stays in the tree. The changing value,count, belongs here. - Inside the State,
widget.plantreads the widget's inputs. setStateruns your change and marks the State as needing a rebuild, sobuildruns again with the new value.
Two lifecycle methods matter early: initState runs once when the State is created (set up controllers or timers there), and dispose runs when it is removed (clean them up there).