Stateful vs. Stateless Widgets
Understanding the two main types of widgets.
StatelessWidget: A widget whose state cannot change over time. It is immutable. Use it for UI elements that don't depend on any internal state, like an icon or a label.\n\n
StatefulWidget: A widget that can change its appearance in response to user interactions or data changes. Use setState() to notify Flutter that the widget's state has changed, triggering a rebuild.
Code Example
import 'package:flutter/material.dart';
class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $_count'),
ElevatedButton(
onPressed: _increment,
child: Text('Increment'),
),
],
);
}
}