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 StatelessWidget has no mutable state. Its build() output depends only on its constructor arguments (and inherited data such as the theme). Examples: a label or an icon button.
  • A StatefulWidget has a separate State object that lives across rebuilds. Calling setState() marks it dirty so build() 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?

Back to question bank