Sub topic 13
Layout: constraints go down, sizes go up
This chapter assumes you know the three trees from earlier chapters: widgets describe, elements persist, and render objects do the layout and painting. It also assumes you have used Row, Column, Padding, and Center. Here you will see how the render object tree decides how big each box is and where it goes.
The one-sentence rule
Flutter's box layout follows a single rule: constraints go down, sizes go up, and the parent sets the position.
- A parent gives each child a
BoxConstraintsobject. It holds a minimum and maximum width and height. - The child picks a size that satisfies those constraints and reports it to the parent.
- The parent decides where to put the child. It stores that position as an offset in the child's
parentData.
A child never knows where it is on screen. It also cannot choose a size outside the constraints it received. Both facts explain most surprising layout behavior.
BoxConstraints
BoxConstraints has four fields: minWidth, maxWidth, minHeight, and maxHeight. How those fields relate gives the constraints a name.
| Kind | Meaning | Example |
|---|---|---|
| Tight | min equals max on an axis, so the child has no choice | The root receives the screen size as tight constraints |
| Loose | min is 0, max is some value, so the child may be any size up to the max | `Center` gives its child loose constraints |
| Bounded | max is a finite number | A `SizedBox` parent with a fixed size |
| Unbounded | max is `double.infinity` | The main axis of a scrolling list |
A tight constraint is the reason Container(width: 100) can appear to be ignored. If it is the root widget, the screen forces it to fill the window. Wrap it in Center or Align and the constraints loosen, so 100 takes effect.
Seeing constraints with LayoutBuilder
LayoutBuilder hands your build function the constraints its parent gave it. Use it to check what a subtree actually receives.
import 'package:flutter/widgets.dart';
void main() => runApp(const ConstraintsDemo());
class ConstraintsDemo extends StatelessWidget {
const ConstraintsDemo({super.key});
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100),
child: LayoutBuilder(
builder: (context, constraints) {
return Text('Got $constraints');
},
),
),
),
);
}
}The root gives tight screen constraints to Directionality, which passes them to Center. Center loosens them to 0..screenWidth by 0..screenHeight. ConstrainedBox then combines its own limits with the incoming ones, so the text sees a maximum of 200 by 100. The printed text should show that range.
How a parent positions a child
Each RenderBox stores its child's position in the child's parentData. For simple boxes this is a BoxParentData with an offset field. The following simplified version of RenderPadding.performLayout shows all three steps of the rule. It is a paraphrase, not the exact framework source.
@override
void performLayout() {
// 1. Constraints down: shrink the space by the padding.
final inner = constraints.deflate(padding);
child!.layout(inner, parentUsesSize: true);
// 3. Parent sets position.
final data = child!.parentData! as BoxParentData;
data.offset = Offset(padding.left, padding.top);
// 2. Sizes up: this box is the child's size plus the padding.
size = constraints.constrain(Size(
child!.size.width + padding.horizontal,
child!.size.height + padding.vertical,
));
}The parentUsesSize: true argument matters. It tells the framework that this parent's own size depends on the child's size, so a child resize must also relayout the parent. If a parent ignores the child's size, it passes false. The framework can then stop the relayout at the child, which is the idea behind relayout boundaries, covered in a later chapter.
Who decides the size
A render object picks its size in one of three ways:
- It fits its children, as
Columndoes along its cross axis. - It fills what it is given, as
Centerdoes. It takes the biggest size allowed. - It uses a fixed size, as
SizedBox(width: 50)does. The size is still passed throughconstraints.constrain, so a tight parent can override it.
A render object that always computes its size from the constraints alone can set sizedByParent to true and compute that size in performResize. Layout then does less work. Most application code never needs this.
Common layout errors
Most layout error messages come from violating the rule. Each one has a mechanical cause.
- "RenderFlex overflowed by N pixels": A
RoworColumnpasses unbounded constraints along its main axis to non-flex children. The children together are larger than theRowitself can be. Wrap the long child inExpandedorFlexibleso it receives a bounded share. - "Vertical viewport was given unbounded height": A
ListViewwas placed inside aColumn. TheColumngives it unbounded height, and a scrollable cannot fill infinity. Give the list a bounded height withExpanded, or useshrinkWrap: truefor short lists. - "BoxConstraints forces an infinite width": A child that wants to fill its parent, such as a widget using
double.infinity, sits in a parent that offers unbounded width.
Here is the overflow fix in code:
import 'package:flutter/widgets.dart';
void main() => runApp(const OverflowFix());
class OverflowFix extends StatelessWidget {
const OverflowFix({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Row(
children: [
Expanded(
child: Text(
'A very long sentence that would overflow a plain Row '
'because Text would ask for all the width it wants.',
),
),
Text('end'),
],
),
);
}
}Row lays out the non-flex Text('end') first, then divides the remaining width among the flex children. Expanded receives a tight width, so its text wraps instead of overflowing.
Layout and the frame
Layout runs after build and before paint. When a render object calls markNeedsLayout, it is added to the pipeline owner's dirty list. During the layout phase, the owner visits these objects from shallowest to deepest and calls layout again. The setter in the custom render object example from earlier follows this pattern: a changed side calls markNeedsLayout, while a changed color calls only markNeedsPaint and skips layout entirely.
Because each parent passes constraints down once and each child returns a size once, a normal box tree is laid out in a single pass. That is why Flutter layout stays cheap, as long as no widget needs to measure its children in several different ways.
Exercise
A Container(width: 100, height: 100, color: red) is the root widget passed to runApp, but it fills the whole screen. Why, and what is the smallest change that makes it 100 by 100?
Show answer
The root render object receives tight constraints equal to the screen size, so the container's requested width and height cannot be honored. Wrapping the container in Center or Align makes the parent give it loose constraints, so it can choose 100 by 100.
Exercise
In a Column, you place a ListView and see "Vertical viewport was given unbounded height". Which constraint caused this, and what are two ways to fix it?
Show answer
The Column passes unbounded maximum height to its non-flex children, and a ListView tries to fill its height. Fix it by wrapping the ListView in Expanded, so it gets a bounded share of the remaining height, or by setting shrinkWrap: true so it sizes itself to its content.