Sub topic 2
How Flutter layout works: constraints down, sizes up
This chapter assumes you can read Dart, write a StatelessWidget, and run a Flutter app. You do not need to know Row, Column, or Stack yet. This chapter explains the rule that decides how those widgets behave.
The one-sentence rule
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 decides the child's position.
A child cannot choose its own position. It cannot choose a size outside the limits its parent gave it. Most surprising layout results come from forgetting one of these two facts.
Each widget that draws something has a render object. Layout is a single walk down the render tree, then a walk back up. This is why layout is fast: each render object is normally visited once per layout pass.
What a constraint is
In box layout, a constraint is a BoxConstraints object with four numbers: minWidth, maxWidth, minHeight, and maxHeight. A child must pick a width between the two width values and a height between the two height values.
Three situations come up constantly:
| Kind | Meaning | Example |
|---|---|---|
| Tight | min equals max, so the child has no choice | `BoxConstraints.tight(Size(100, 100))` |
| Loose | min is 0, so the child may pick any size up to the max | `BoxConstraints.loose(Size(300, 600))` |
| Unbounded | max is `double.infinity` | The main axis of a scrolling list |
A bounded constraint has a finite max. An unbounded constraint has an infinite max in at least one direction. Unbounded constraints are not wrong in themselves. They become an error only when a widget needs a finite size and cannot find one, which is covered below.
Why `Container(width: 100)` can ignore you
Run this program:
import 'package:flutter/material.dart';
void main() {
runApp(Container(width: 100, height: 100, color: Colors.red));
}You might expect a small red square. You get a red screen. The root widget receives tight constraints equal to the screen size. A Container inside tight constraints has no room to choose, so its width and height are ignored.
The fix is to put a widget between the root and the Container that loosens the constraints. Center does this:
import 'package:flutter/material.dart';
void main() {
runApp(
Center(
child: Container(width: 100, height: 100, color: Colors.red),
),
);
}Center receives tight screen constraints. It passes its child loose constraints: the minimum drops to 0 and the maximum stays at the screen size. The Container can now pick 100 by 100. Center then positions it in the middle, which is the parent's job.
Reading constraints with LayoutBuilder
You do not need to guess what constraints a widget receives. LayoutBuilder hands them to you in its builder callback. This program prints the constraints at two places in the tree:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Demo())));
class Probe extends StatelessWidget {
const Probe({super.key, required this.label});
final String label;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return Text('$label: $constraints');
},
);
}
}
class Demo extends StatelessWidget {
const Demo({super.key});
@override
Widget build(BuildContext context) {
return const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Probe(label: 'In a Column'),
Row(children: [Probe(label: 'In a Row')]),
],
);
}
}On a typical phone you will see output like BoxConstraints(0.0<=w<=393.0, 0.0<=h<=Infinity) for the Column child. The Row child shows 0.0<=w<=Infinity with a finite height range. The exact numbers depend on the device. The pattern does not:
- A
Columngives its children the column's own width limit but an unbounded height. - A
Rowgives its children the row's own height limit but an unbounded width.
This is the first appearance of an important idea. Along the main axis, a Row or Column lets non-flexible children be as large as they want, so it can see how much room they need. The next chapters build on this.
Widgets that change constraints
Many layout widgets exist only to modify the constraints passed to their child. The table lists the ones you will use most.
| Widget | What it does to the child's constraints |
|---|---|
| `Center`, `Align` | Loosens them (minimum becomes 0) and positions the child |
| `SizedBox(width: w, height: h)` | Forces tight constraints, if the parent allows those values |
| `ConstrainedBox` | Combines extra constraints with the incoming ones |
| `Padding` | Shrinks the max by the padding, then adds the padding to the child's size |
| `UnconstrainedBox` | Removes the incoming constraints, so the child can be any size, which can cause overflow |
Notice the phrase "if the parent allows those values". A widget's own constraints are always clamped to what the parent gave it. If a SizedBox(width: 500) sits inside a parent that allows at most 300, the box is 300 wide. The parent's limit always wins.
import 'package:flutter/material.dart';
void main() {
runApp(
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 200),
child: Container(
height: 50,
color: Colors.blue,
child: const SizedBox(width: 500),
),
),
),
);
}The ConstrainedBox caps the width at 200. The Container has no explicit width, so it sizes to fit its child. The child asks for 500 but is clamped, so the blue bar is 200 wide.
How a widget picks its size
Within the constraints it receives, a render object usually follows one of three strategies:
- Be as big as possible.
Centerexpands to the largest size allowed. AContainerwith no child and no explicit size does the same. - Match the child. A
Padding, or aContainerthat has a child but no explicit size, wraps its child. - Have a fixed natural size.
Textmeasures its content and is only as wide as the text needs, up to the max width. Past that, the text wraps to another line.
Knowing which strategy a widget uses explains most "why is this widget huge or tiny?" questions. A widget that expands fills any bounded space. A widget that wraps its child shrinks to its content.
Limits of the model
Because a child cannot know where its parent will place it, some things are not possible in a single pass:
- A widget cannot ask "where am I on the screen?" during layout. It learns that only after layout, through a
RenderBoxor aGlobalKey. - A widget cannot freely resize its parent. If a child needs more room than allowed, it must either get clamped, overflow, or ask a parent that can scroll.
- Constraints are only a set of limits. A widget may be smaller than the maximum, and a parent is free to align a smaller child however it likes.
Unbounded constraints and the errors they cause
A scrollable widget such as ListView is happy to be larger than the screen along its scroll direction, but it must know how tall to make its viewport. When its parent gives it an unbounded maximum height, it cannot choose, and Flutter reports a "Vertical viewport was given unbounded height" error. A Column inside another Column without a bounded height, or a ListView directly inside a Column, triggers this. The cure is to bound the height: wrap the ListView in an Expanded or a SizedBox with a fixed height. Later chapters work through these fixes in detail.
Summary
- Constraints go down, sizes go up, and the parent sets position.
- Tight constraints leave the child no choice. Loose constraints give a range. Unbounded constraints have an infinite max.
- A widget's own
widthandheightare requests. The parent's constraints can override them. LayoutBuildershows you exactly what a widget was given.
Exercise
In runApp(Container(width: 100, height: 100, color: Colors.red)), why does the container fill the whole screen? Name one widget you can insert above the Container to make it 100 by 100, and explain what that widget changes.
Show answer
The root widget receives tight constraints equal to the screen size, so the Container has no freedom to choose 100 by 100 and its width and height are ignored. Wrapping it in Center (or Align) loosens the constraints so the minimum becomes 0 while the maximum stays at the screen size. The Container can then pick 100 by 100, and Center positions it in the middle.
Exercise
A SizedBox(width: 500, child: Text('Hi')) is placed inside a ConstrainedBox with BoxConstraints(maxWidth: 300), which sits inside a Center. How wide is the SizedBox, and why?
Show answer
It is 300 wide. The Center loosens the screen constraints, and the ConstrainedBox then caps the maximum width at 300. The SizedBox asks for 500, but a child's size is clamped to its parent's constraints, so the parent's limit wins.