Sobes.tech
Junior — Middle

Explain the concept of StatefulWidget in Flutter and how it differs from StatelessWidget.

sobes.tech AI

Answer from AI

In Flutter, a StatefulWidget is a widget that can change its state during the app's runtime. It stores its state in a separate State object, and when this state changes, the setState() method is called to update the UI.

In contrast, a StatelessWidget has no internal state and is built solely based on the parameters passed to it. It does not change after creation.

Example:

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

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

  void _increment() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Counter: \\$_counter'),
        ElevatedButton(onPressed: _increment, child: Text('Increase')),
      ],
    );
  }
}

Here, CounterWidget is a StatefulWidget because the counter value changes and affects the UI. If the state didn't change, a StatelessWidget could be used.

Explain the concept of StatefulWidget in Flutter and… - sobes.tech