TechnicalEasy Flutter
What is the difference between a StatelessWidget and a StatefulWidget in Flutter?
Asked for Mobile Developer
Why they ask this: The first concept of every Flutter app; it shows you understand how the UI rebuilds.
Answer
- A
StatelessWidgethas no mutable state. Itsbuild()output depends only on its constructor arguments (and inherited data such as the theme). Examples: a label or an icon button. - A
StatefulWidgethas a separateStateobject that lives across rebuilds. CallingsetState()marks it dirty sobuild()runs again. Examples: a form, a counter, a tab view.
text
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => count++),
child: Text('Tapped $count times'),
);
}
}Use the State lifecycle methods: initState() for setup and dispose() to release controllers, streams and timers.
Can you explain this in your own words?