Flutter · One codebase, native feel
When do you use a StatelessWidget versus a StatefulWidget?
Short answer
Use StatelessWidget when the UI depends only on constructor inputs and inherited data. Use StatefulWidget when the widget owns mutable state that must trigger rebuilds over its lifetime.
A StatelessWidget has no mutable fields and builds from its properties plus inherited widgets. A StatefulWidget delegates to a State object, which persists across rebuilds and can call setState to schedule a new build. The widget is still immutable; the State holds the changing data.
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0;
void increment() {
setState(() {
count += 1;
});
}
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: increment,
child: Text('Count: ' + count.toString()),
);
}
}- Local ephemeral state such as a checkbox, animation or text controller belongs in State
- Shared application state is better held in a notifier, bloc or repository
- State should be disposed correctly, including controllers, subscriptions and tickers
- If only a child needs to rebuild, lift the state down or use a listenable builder
Common mistakes
Calling setState for values that do not affect the UI wastes frames. Starting async work in build causes repeated requests. Storing derived data in State invites inconsistency; compute it during build or in a getter when cheap.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What exactly does setState do?
- 2Where should a TextEditingController be created and disposed?
- 3Why is starting a network request in build a bug?
- 4How would you rebuild only one part of a stateful screen?
Say it in the interview
I use a StatelessWidget when the output is a pure function of its inputs and inherited context. I use a StatefulWidget when the widget owns mutable state across frames, like a form controller or an animation. The State object persists while the widget is rebuilt, and setState marks it dirty. I keep shared app state out of State objects and dispose every controller and subscription.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Flutter mock interview and get scored feedback on depth, clarity and confidence.