D
Flutter CoreBeginner10 XP3 min read

What is the difference between StatelessWidget and StatefulWidget?

TL;DR: StatelessWidget is immutable and rebuilds only when its parent provides new configuration; StatefulWidget owns mutable state in a separate State object that survives rebuilds and can trigger them via setState().

Full Answer

The core difference is about state ownership and mutability.

StatelessWidget

  • Immutable — all fields must be final
  • build() is called whenever the parent rebuilds with new data
  • No internal state — describe UI purely from incoming properties
  • Lighter weight — no State object allocation

StatefulWidget

  • Has a companion State<T> object that persists across rebuilds
  • Can call setState() to schedule a rebuild with new data
  • State object is created once; widget can be recreated many times
  • Use when widget needs to respond to user interaction, timers, or streams
⚠️

Prefer StatelessWidget whenever possible. Excessive StatefulWidgets lead to unnecessary rebuilds and harder-to-test code. Consider using state management solutions for complex state.

Code Examples

dartStatelessWidget vs StatefulWidget
Output
Counter button starts at 0 and increments with each tap. GreetingCard displays its name prop unchanged.

Common Mistakes

  • Storing state in a StatelessWidget via non-final fields — will not trigger rebuilds.
  • Calling setState() after dispose() — causes errors; always check mounted first.

Interview Tip

💡

The key insight is that StatefulWidget itself is also immutable — only the State object is mutable. The widget is just a configuration object; the State holds the live data.

#widgets#stateless#stateful#state