class WidgetName extends StatefulWidget {
const WidgetName({ super.key });
@override
State<WidgetName> createState() => _WidgetNameState();
}
class _WidgetNameState extends State<WidgetName> {
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(color: const Color(0xFFFFE306));
}
}
Stateful widgets are used to define states in Flutter that can be modified and bound with other widgets. Creating a stateful widget in flutter is different from creating a stateless widget. You can create stateful widgets by inheriting StatefulWidget class in your class and then create another class for the state definition of this class as created in the code snippet.
In the code snippet, we have created a Fruit class and its state class is _FruitState where we are defining a state _quantity which can be changed on button click.
# code example 2
class Fruit extends StatefulWidget {
const Fruit({
Key key,
this.color = const Color(0xffFF0000),
this.name,
}) : super(key: key);
final Color color;
final String name;
@override
_FruitState createState() => _FruitState();
}
class _FruitState extends State<Fruit> {
double _quantity = 3;
void increaseQty() {
setState(() { _quantity += 1; });
}
@override
Widget build(BuildContext context) {
return Container(
color: widget.color,
child: FlatButton(
onPressed: increaseQty(),
child: Text(widget.name),
),
);
}
}
0 Comments