stateful
A stateful widget itself is immutable, but it will create a state class which
holds mutable information. First, flutter creates the stateful element for the
stateful widget. Then, it calls the widget's createState()
method. That method
creates a state object for the element. Finally, the build()
method on the
state object is called.
In this example the state object is creating a Text widget. The text widget makes a Text element which becomes a child of the Stateful element (not the state object).
class ItemCounter extends StatefulWidget {
final String name;
const ItemCounter({Key? key, required this.name}) : super(key: key);
@override
_ItemCounterState createState() => _ItemCounterState();
}
class _ItemCounterState extends State<ItemCounter> {
int count = 0;
@override
Widget build(BuildContext context) {
return Text('${widget.name}: $count');
}
}
gesture detector
In the above example the count variable is able to change, but nothing
actually changes it. We can instead create a gesture widget with the text widget
as its child. The gesture is onTap()
so the number can be incremented when
tapped.
class _ItemCounterState extends State<ItemCounter> {
int count = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
count++;
});
},
child: Text('${widget.name}: $count'));
}
}