flutter

Create stateful widget in Flutter

In this tutorial, we will learn how to create a stateful widget in Flutter. A stateful widget is a widget that has a mutable state. The state of a widget can change during the lifetime of the widget. For example, if a widget is a counter, the state of the widget is the current count. When the user presses a button, the state of the widget changes, and the widget is rebuilt with the new state.

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),
            ),
        );
    }
}
Was this helpful?