Sub topic 2
How Flutter layout works: constraints down, sizes up
This chapter assumes you can write StatelessWidget and StatefulWidget classes. It also assumes you have used Row, Column, Scaffold and ListView, and can run a Flutter app on a device, emulator or desktop target. Every responsive technique in the later chapters rests on the layout rules below. If you learn these rules first, you can predict most layout errors before they happen.
The rule in one sentence
Flutter's layout rule has three parts:
- A parent passes constraints down to each child.
- The child chooses a size within those constraints and passes it back up.
- The parent then decides the child's position.
A child never decides where it sits, and it never gets to ignore its constraints. A widget also does not know its own size until its parent has given it constraints and it has laid itself out.
Each render object in the tree repeats this exchange. Layout is a single pass from the root down and back up, so it is fast. The trade-off is that a child cannot negotiate. It receives a range and picks a size from it.
BoxConstraints
Most widgets are laid out with a BoxConstraints object. It holds four numbers: minWidth, maxWidth, minHeight and maxHeight. The child must return a size where the width is between the two widths and the height is between the two heights.
The terms below describe the constraints you will meet most often.
| Term | Meaning | Example |
|---|---|---|
| Tight | Min equals max, so the child has no choice | The root widget, which gets exactly the window size |
| Loose | Min is 0, so the child can be anything up to the max | What `Center` and `Align` pass to their child |
| Bounded | The max is a finite number | A child of `Center` in a normal window |
| Unbounded | The max is `double.infinity` | The main axis of a `Column`, `Row` or scrollable |
A widget with a fixed size, such as Container(width: 500), is really asking for a tight constraint of 500. The parent's constraints are applied first, so the request is clamped. If the parent allows at most 200, the container is 200 wide.
Watching constraints change
You can see the constraints by printing them. LayoutBuilder is covered properly in a later chapter. Here it is only a probe that shows what the parent passed down.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: ProbeDemo())));
class ConstraintsProbe extends StatelessWidget {
const ConstraintsProbe({super.key, required this.label});
final String label;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => Text('$label: $constraints'),
);
}
}
class ProbeDemo extends StatelessWidget {
const ProbeDemo({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 200),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ConstraintsProbe(label: 'In Column'),
Container(
width: 500,
height: 50,
color: Colors.indigo,
child: const ConstraintsProbe(label: 'In Container'),
),
],
),
),
);
}
}Run it and read the output on screen. Here is what each widget does:
Centerpasses loose constraints with the window's width and height as the maximum.ConstrainedBoxnarrows the maximum width to 200.Columnkeeps that width limit but passesInfinityas the maximum height to its children, because a column lets children grow along its main axis.Container(width: 500)asks for 500. The 200 limit overrides the request, so the container is 200 wide.- The probe inside the container sees a tight width of 200 and a tight height of 50.
The container's width: 500 is not an error. It is a request, and the parent's constraints take priority.
Why a widget does not just fill the screen
Beginners often write Container(width: 100, height: 100) as the root widget and are surprised that it fills the window. At the root, the constraints are tight at the window size. A tight constraint leaves the child no choice, so the 100 by 100 request is ignored. Put the container inside Center and the constraints become loose, so the container is 100 by 100.
Many widgets size themselves in one of three ways:
- Fill the maximum. A
Containerwith no child and no size,CenterandListViewdo this when the constraint is bounded. - Fit the child.
Padding,Alignwith size factors, and aContainerwith a child but no size wrap their content. - Use a fixed size.
SizedBox(width: 50)asks for 50, within the limits.
The same widget can behave differently under different constraints. That is the foundation of responsive layout. You do not set a screen size in each widget. You let the parent's constraints change and the widget responds.
Flex layouts and unbounded constraints
Row and Column run a two-step algorithm along their main axis:
- They lay out the non-flexible children with an unbounded main-axis maximum, so those children can take their natural size.
- They split the remaining space between the flexible children, which are the ones wrapped in
ExpandedorFlexible.
On the cross axis, they pass the incoming limit as a loose constraint. With CrossAxisAlignment.stretch, they pass a tight constraint instead.
Unbounded constraints cause most of the layout exceptions you will see. A widget that wants to fill the available space cannot do that when the space has no end. Two common cases follow.
| Error text | Cause | Fix |
|---|---|---|
| "Vertical viewport was given unbounded height" | A `ListView` inside a `Column` or another scrollable, with no height limit | Wrap the list in `Expanded`, give it a `SizedBox` height, or set `shrinkWrap: true` for a short list |
| "RenderFlex children have non-zero flex but incoming height constraints are unbounded" | An `Expanded` inside a `Column` that is itself in an unbounded area | Give the column a bounded height, or remove the `Expanded` |
| "A RenderFlex overflowed by N pixels" | The children are wider or taller than the maximum allows | Wrap the children in `Expanded`, `Flexible` or `Wrap`, or shorten the content |
Here is the first case, fixed. The Column sits in a bounded area. Expanded hands the ListView the space left after the title, so the list is bounded and can scroll.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: TitledList())));
class TitledList extends StatelessWidget {
const TitledList({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
const Padding(
padding: EdgeInsets.all(16),
child: Text('Inbox', style: TextStyle(fontSize: 24)),
),
Expanded(
child: ListView.builder(
itemCount: 50,
itemBuilder: (context, i) => ListTile(title: Text('Message $i')),
),
),
],
);
}
}Without the Expanded, the ListView receives an unbounded height and throws the first exception in the table. The widget wants to be as tall as its content, which could be 50 items or 50,000. It cannot do that and also be a viewport that scrolls.
The shrinkWrap: true fix makes the list as tall as all its children. That forces Flutter to measure every item, so it loses the lazy loading that makes ListView.builder cheap. Use it only for short lists.
Constraints and responsive design
The model has two consequences for the design decisions in later chapters.
First, a widget decides what to show based on constraints it receives, not on a global screen size. A panel placed in a narrow sidebar gets narrow constraints even on a wide monitor. A layout rule that looks at the whole window will be wrong for that panel. LayoutBuilder exposes the parent's constraints and MediaQuery exposes the window. You will choose between them in the next chapters, and this point is why the choice matters.
Second, a widget cannot ask "how big will I be?" while it is building. Its size depends on layout, which happens after build. If you need the size at build time, read the constraints with LayoutBuilder. Do not read a size from a GlobalKey after layout and call setState with it. That approach lags a frame behind and can cause a loop of rebuilds.
Debugging constraint problems
Four habits help when a layout does not do what you expect:
- Read the exception text. Flutter names the widget that received unbounded constraints and often lists the ancestor chain.
- Open the Flutter DevTools widget inspector and select a widget. The Layout Explorer shows the constraints and the size of the selected widget, and of its parent.
- Add a
ConstraintsProbe, as above, at the point where the layout goes wrong. - Set
debugPaintSizeEnabled = true(frompackage:flutter/rendering.dart) in debug builds to outline every render box.
When a widget is "too big", find the nearest ancestor that gives a tight or unbounded constraint. When it is "too small", look for an ancestor that passes loose constraints, such as Center or Align, and for a child that sizes to its content.
Exercise
A Center is the root of the screen, which is 400 by 800. Its child is ConstrainedBox(constraints: BoxConstraints(minWidth: 100, maxWidth: 200), child: Container(width: 50, height: 50)). What width and height does the Container end up with, and why?
Show answer
The container is 100 wide and 50 tall. Center passes loose constraints of 0 to 400 by 0 to 800. ConstrainedBox applies its own limits within them, so its child gets a width between 100 and 200 and a height between 0 and 800. The container asks for a tight width of 50, which is below the minimum, so it is clamped up to 100. The height of 50 is inside the allowed range, so it stays 50.
Exercise
A screen has Column(children: [Text('Results'), ListView(children: items)]) and throws "Vertical viewport was given unbounded height". Explain the cause in terms of constraints, and give a fix that keeps lazy loading available.
Show answer
A Column gives non-flex children an unbounded maximum height. A ListView cannot size itself to a range with no upper limit, because it is a scrollable viewport that wants to fill the space it is given. Wrap the ListView in Expanded so it receives the remaining bounded height, and use ListView.builder if the list is long so items are built lazily. Avoid shrinkWrap: true, because it gives the list a bounded height by measuring every item and removes the lazy loading.