Junior — Middle
What is the class StatefulWidget and in what cases is it used in Flutter?
sobes.tech AI
Answer from AI
In Flutter, the StatefulWidget class is used to create widgets that can change their state during the application's runtime. Unlike StatelessWidget, which is immutable, StatefulWidget stores its state in a separate State object, allowing the interface to be dynamically updated when data changes.
It is used when you need to respond to user input, asynchronous operations, animations, or any other changes affecting the widget's display.
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')),
],
);
}
}