What is StatelessWidget and StateFulWidget?

What is StatelessWidget and StateFulWidget?

ยท

2 min read

StatelessWidget:

A StatelessWidget in Flutter is a widget that, once built, cannot be changed. It's like a snapshot of a user interface at a specific moment. If the information or appearance of the widget needs to be altered, you create a new instance of the widget.

Consider a simple text display widget as an example. You might create a Text widget to show the title of a page. Since the title typically doesn't change during the lifetime of that screen, you can use a StatelessWidget. Once the title is set, it remains the same until you navigate to a different screen.

class TitleWidget extends StatelessWidget {
  final String title;

  TitleWidget(this.title);

  @override
  Widget build(BuildContext context) {
    return Text(title, style: TextStyle(fontSize: 24));
  }
}

StatefulWidget:

In contrast, a StatefulWidget can change or update its appearance dynamically. It consists of two parts: the widget itself and an associated mutable state object. When the state changes, the widget is rebuilt, reflecting the updated information.

Imagine a simple counter app where you press a button to increase the count. The count is the mutable state here. You would use a StatefulWidget to manage the changing count.

class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int count = 0;

  void incrementCounter() {
    setState(() {
      count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $count', style: TextStyle(fontSize: 24)),
        ElevatedButton(
          onPressed: incrementCounter,
          child: Text('Increment'),
        ),
      ],
    );
  }
}

Here, the _CounterWidgetState class holds the mutable state (count), and the setState method is used to notify Flutter that the state has changed, triggering a rebuild of the widget with the updated count.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย