Sub topic 13
Layout: Constraints Go Down, Sizes Go Up
Prerequisites and mental model
Assume you know basic Dart and can compose Flutter widgets such as Row, Column, Padding, and Text.
Flutter layout follows one rule:
- A parent passes constraints down to its child.
- The child chooses a size that satisfies those constraints.
- The parent receives that size and chooses the child’s position.
A constraint contains minimum and maximum widths and heights. A tight constraint has equal minimum and maximum values, so the child must use one exact size. A loose constraint allows the child to choose any size above the minimum.
Layout happens after build. The build method creates widget configuration. During layout, render objects calculate sizes and positions.
Passing constraints through widgets
A screen usually gives its root a bounded size. Each widget then modifies or forwards those constraints.
For example, SizedBox can impose an exact width and height. Padding reduces the space available to its child. Row divides horizontal space among its children. Expanded tells a flex widget to assign remaining space to a child.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: ConstraintDemo()));
}
class ConstraintDemo extends StatelessWidget {
const ConstraintDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SizedBox(
width: 280,
height: 160,
child: Row(
children: [
Expanded(
child: ColoredBox(
color: Colors.blue,
child: Center(
child: Text(
'Expanded',
style: TextStyle(color: Colors.white),
),
),
),
),
SizedBox(
width: 80,
child: ColoredBox(
color: Colors.orange,
child: Center(child: Text('80')),
),
),
],
),
),
),
);
}
}The Center receives the screen’s constraints and positions the SizedBox in the middle. SizedBox gives Row a width of 280 and a height of 160. Row gives the fixed child a width of 80, then gives the remaining 200 pixels to Expanded. Each child reports its size, and Row positions them side by side.
Common constraint errors
An unbounded constraint has an infinite maximum in one direction. A Column inside a vertically scrolling ListView often receives unbounded height. Putting Expanded there fails because Expanded needs a finite amount of remaining height to divide.
Similarly, placing ListView directly inside a Column can fail because both widgets want to control vertical size. Give the ListView a finite height with Expanded or SizedBox.
double.infinity also fails under an unbounded constraint. It requests an infinite size, but no finite layout can satisfy that request.
Exercise
A ListView is placed directly inside a Column and reports an unbounded-height error. What change commonly fixes it?
Show answer
Wrap the ListView in Expanded when the Column has a finite height, or wrap it in a SizedBox with an explicit height.