Responsive Widgets
Sprout looks right on your phone. Open it on a tablet and the plant list stretches into long, thin rows with a sea of empty space. A responsive layout reads how much room it has and arranges itself to fit, whether that is a small phone, a tablet in landscape, or a resizable desktop window.
The rule
Measure the space you are given, then share it out.
Measuring
// The whole window
final width = MediaQuery.sizeOf(context).width;
// Only the space this widget's parent gives it
LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 600) {
return const PlantListView(); // one column
}
return const PlantGridView(); // cards in a grid
},
);MediaQuery answers "how big is the window?". LayoutBuilder answers "how much room do I have?", which is usually the better question for a component.
Sharing out
ExpandedandFlexible, inside aRoworColumn, split the leftover space byflexratio.Wraplays children in a line and moves to the next line when they no longer fit.GridViewwith a maximum tile width lets the column count follow the width.SafeAreakeeps content clear of notches and system bars.
Row(
children: [
Expanded(flex: 2, child: PlantDetails(plant)),
Expanded(flex: 1, child: WateringHistory(plant)),
],
);Here the details get two thirds of the width and the history one third, on any screen.
The shortcut
Think in breakpoints and ratios, never in fixed pixel widths.
Measure
Wrap the area in
LayoutBuilderand readconstraints.maxWidth.
The trap is a fixed width like SizedBox(width: 400) in a Row. On a narrow phone the row runs out of room and Flutter paints the yellow-and-black overflow stripes.
Drills
Answer fast — trust the rule.
Which widget reports the space its parent gives it?
In a Row, Expanded(flex: 3) and Expanded(flex: 1) share 800 pixels. How wide is the first?
Tag chips overflow the right edge of a phone screen. Which widget moves them onto a new line?
Sprout's plant panel sits beside a 400-pixel menu in a 1000-pixel window. What does MediaQuery.sizeOf(context).width return inside the panel?
Remember
- Measure the space you are given, then share it out.
- Think in breakpoints and ratios, not fixed pixel widths.
- Trap:
MediaQuerymeasures the window, not your widget, and fixed widths overflow.
