Stateless Widgets
Sprout's home screen is a list of plants, each row showing a name and "water in 2 days". Every row looks the same apart from its data. In Flutter, that row is a widget: a small, reusable description of part of the screen.
The rule
A stateless widget turns its inputs into a picture, nothing more.
class PlantTile extends StatelessWidget {
const PlantTile({super.key, required this.name, required this.daysLeft});
final String name;
final int daysLeft;
@override
Widget build(BuildContext context) {
return ListTile(
leading: const Icon(Icons.local_florist),
title: Text(name),
subtitle: Text('Water in $daysLeft days'),
);
}
}- The fields are
final. A widget is an immutable description; it never edits itself. - The
constconstructor lets Flutter reuse identical instances, such asconst Icon(...), instead of rebuilding them. buildreturns more widgets.ListTile,IconandTextare widgets too, so the screen is a tree of widgets inside widgets.super.keypasses an optional key to the parent class. Keys help Flutter tell apart items of the same type, for example when a list is reordered.
To show a different plant, the parent simply creates another PlantTile with other arguments: PlantTile(name: 'Cactus', daysLeft: 12).
The shortcut
Ask "Does this widget ever need to change a value by itself?" If the only way its content changes is the parent handing it new arguments, it is stateless.
The plant row
Shows a name and a number given by the parent. It never changes them itself. Stateless.
The trap is adding a non-final field to a stateless widget and changing it. The screen will not update, and the analyzer warns you, because nothing tells Flutter to rebuild.
Drills
Answer fast — trust the rule.
Which method must a StatelessWidget override?
Why are a stateless widget's fields declared final?
How do you make a PlantTile show "Cactus" instead of "Fern"?
What does the const in const Icon(Icons.local_florist) allow?
Remember
- A stateless widget turns its inputs into a picture, nothing more.
- Shortcut: if only the parent changes its content, it is stateless.
- Trap: mutable fields in a stateless widget never refresh the screen.
