Sub topic 5
Reacting to available space with LayoutBuilder
This chapter assumes you know Dart 3 switch expressions, can build widget trees with StatelessWidget and StatefulWidget, and know that constraints flow down the tree and sizes flow up. It also assumes you know how MediaQuery.sizeOf reports the window size. You will use LayoutBuilder to make a widget choose its layout from the space its parent gives it.
What LayoutBuilder does
LayoutBuilder is a widget whose builder callback receives a BuildContext and a BoxConstraints. Those constraints are the ones the parent passes to the LayoutBuilder itself. The callback returns the child subtree, so the subtree can depend on the space it will actually get.
Ordinary widgets build before layout. LayoutBuilder delays building its child until layout time, when the constraints are known. Flutter calls the builder again when:
- the parent's constraints change, for example when the window is resized or a sibling changes size
- the
LayoutBuilderwidget is rebuilt with a new builder closure
The block above is only a placeholder to keep the numbering clear; the real diagram follows.
A first example
The helper below maps a width to a Material 3 window-size class. The boundaries are 600 and 840 logical pixels. Later chapters cover breakpoints in more detail.
enum WindowSize { compact, medium, expanded }
WindowSize windowSizeFor(double width) {
if (width < 600) return WindowSize.compact;
if (width < 840) return WindowSize.medium;
return WindowSize.expanded;
}AdaptiveBody uses the helper inside a LayoutBuilder. The switch expression covers every enum value, so the compiler reports a missing case if you add a value to WindowSize.
import 'package:flutter/material.dart';
class AdaptiveBody extends StatelessWidget {
const AdaptiveBody({super.key});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final size = windowSizeFor(constraints.maxWidth);
return switch (size) {
WindowSize.compact => const Center(child: Text('One pane')),
WindowSize.medium => const Center(child: Text('Two panes, narrow')),
WindowSize.expanded => const Center(child: Text('Two panes, wide')),
};
},
);
}
}To run it, put the enum, the helper and the class in one file, then add this entry point:
void main() {
runApp(const MaterialApp(home: Scaffold(body: AdaptiveBody())));
}Resize a desktop window or use a browser target and watch the text change at 600 and 840 pixels.
LayoutBuilder versus MediaQuery.sizeOf
Both can drive a layout switch, but they measure different things.
| Question | `MediaQuery.sizeOf(context)` | `LayoutBuilder` |
|---|---|---|
| What does it measure? | The size of the whole window or view | The constraints from the widget's own parent |
| Reacts to a sibling or parent changing size? | No | Yes |
| Where does the logic run? | In `build` | In the builder, during layout |
| Rebuilds when | Window size changes | The parent's constraints change |
| Best for | App-level decisions, such as the navigation shell | Component-level decisions, such as a card or a pane |
Use MediaQuery.sizeOf when the decision is about the device or window. Choosing between a bottom bar and a rail is one example. Use LayoutBuilder when a reusable widget must work in any slot, for example a full-width list, a half-width pane or a sidebar.
Suppose a two-pane screen on a 1200-pixel window gives the detail pane 700 pixels. A detail widget that asks MediaQuery.sizeOf sees 1200 and picks the expanded layout, which may be too wide for its slot. Asked through LayoutBuilder, the same widget sees 700 and picks the medium layout.
Prefer MediaQuery.sizeOf to MediaQuery.of(context).size. The sizeOf form subscribes only to size changes. of subscribes to every MediaQuery field, such as the keyboard inset, and causes extra rebuilds.
Adapting a single component
LayoutBuilder works at any level of the tree. The next widget changes its own internal direction depending on its width.
import 'package:flutter/material.dart';
class ProfileTile extends StatelessWidget {
const ProfileTile({super.key});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
const avatar = CircleAvatar(radius: 24, child: Icon(Icons.person));
const name = Text('Ada Lovelace');
if (constraints.maxWidth >= 300) {
return const Row(
mainAxisSize: MainAxisSize.min,
children: [avatar, SizedBox(width: 12), name],
);
}
return const Column(
mainAxisSize: MainAxisSize.min,
children: [avatar, SizedBox(height: 8), name],
);
},
);
}
}
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Row(
children: [
Expanded(child: Center(child: ProfileTile())),
Expanded(child: Center(child: ProfileTile())),
],
),
),
),
);
}Each tile sits in an Expanded slot, so each one gets half the window. On a 700-pixel window each tile sees maxWidth of 350 and uses the row. On a 500-pixel window each sees 250 and switches to the column. A MediaQuery check would give both tiles the same answer for the whole window, whatever slot they sit in.
Reading the constraints correctly
BoxConstraints has four values: minWidth, maxWidth, minHeight and maxHeight. For layout switching you almost always read maxWidth. A few details matter:
maxWidthis the most space the child may use, not the size the child will have. ACenterancestor gives its child loose constraints, somaxWidthstays large even if the child is small.constraints.biggestandconstraints.smallestreturn the largest and smallest sizes allowed.hasBoundedWidthandhasBoundedHeighttell you whether the maximum is finite.
Unbounded constraints
Some parents give a child an infinite maximum on one axis. Non-flex children of a Row get unbounded width. Children of a horizontal ListView or SingleChildScrollView do too. In those cases constraints.maxWidth is double.infinity.
windowSizeFor(double.infinity) returns WindowSize.expanded, which is rarely what you want, and nothing warns you. Guard against it:
import 'package:flutter/material.dart';
Widget buildForConstraints(BoxConstraints constraints) {
if (!constraints.hasBoundedWidth) {
return const Text('Width is unbounded; using a fixed layout');
}
final size = windowSizeFor(constraints.maxWidth);
return Text('Window size class: ${size.name}');
}Alternatively, wrap the LayoutBuilder in an Expanded or a SizedBox so that its parent bounds the width.
Gotchas and limits
- No intrinsic dimensions.
LayoutBuildercannot answer intrinsic size queries. Placing one underIntrinsicWidth,IntrinsicHeightor other widgets that ask for intrinsic sizes throws aFlutterErrorat runtime. Restructure so theLayoutBuilderis outside those widgets, or pass a fixed size instead. - Do not call
setStatein the builder. The builder runs during layout. Changing state there triggers a rebuild during layout, and Flutter reports an error. Compute values fromconstraintsand return widgets. Do not store them. - Keep the builder cheap. It runs on every constraint change, and during a window drag that can be every frame. Move expensive work out of it, and use
constwidgets where possible. - Place it at the right level. A
LayoutBuilderat the top of a screen sees the screen's width. If you want a pane's width, put the builder inside the pane. The same code gives different answers at different depths. - Constraints are not the final size. The builder sees what the parent allows. The widget's final size comes from the child you return, and it may be smaller.
- Scrolling content. Inside a vertical scrollable,
maxHeightis infinite. ReadmaxWidthfor such decisions. For slivers, useSliverLayoutBuilder, which gives youSliverConstraintsinstead.
Choosing between the two
Use this decision list when a layout choice comes up:
- Does the choice depend on the device or window as a whole, such as the navigation pattern or the page's overall column structure? Use
MediaQuery.sizeOf. - Does the widget get reused in slots of different sizes, or share a screen with siblings that change its width? Use
LayoutBuilder. - Is it a scrolling sliver? Use
SliverLayoutBuilder. - Can plain
Expanded,Flexible,Wrapor a grid delegate do the job without a branch? Use those, because they need no builder.
You can mix them. A shell widget can read MediaQuery.sizeOf to pick a navigation widget, and each page inside can use LayoutBuilder to organize its own content.
Exercise
A DetailView widget calls windowSizeFor(MediaQuery.sizeOf(context).width) to decide between a one-column and a two-column layout. On a 1000-pixel window it sits in a 350-pixel right pane, and it chooses the two-column layout, which overflows. What change fixes this, and why does it work?
Show answer
Wrap the body in a LayoutBuilder and call windowSizeFor(constraints.maxWidth). MediaQuery.sizeOf reports the whole window (1000 pixels, expanded), while constraints.maxWidth reports the 350 pixels the pane gives the widget, which maps to compact and selects the one-column layout. Also check constraints.hasBoundedWidth in case a parent leaves the width unbounded.
Exercise
You add a LayoutBuilder inside a horizontal ListView item and read constraints.maxWidth. The layout always takes the expanded branch, whatever the window size. What is happening, and how do you fix it?
Show answer
A horizontal ListView gives its children unbounded width, so maxWidth is double.infinity. That value is always at least 840, so windowSizeFor returns WindowSize.expanded. Give the item a bounded width, for example with a SizedBox(width: ...), or check constraints.hasBoundedWidth and use a fixed fallback layout when it is false.