Sub topic 3
Layouts that flex: Expanded, Flexible, Wrap and AspectRatio
This chapter assumes you know how constraints flow down and sizes flow up, and that you are comfortable with Row, Column, Scaffold and Dart 3 syntax. The widgets here let a layout take the space it is given instead of fixed sizes. They need no breakpoints, so they are the first tool to reach for.
How Row and Column share space
Row and Column are both built on the same render object, RenderFlex. The main axis is horizontal for Row and vertical for Column. Along the main axis, RenderFlex lays out children in three steps:
- It lays out every child that is not flexible, such as
Icon,SizedBoxorTextwith no wrapper. Each gets an unbounded main-axis constraint and the cross-axis constraint of the parent. - It subtracts their sizes from the available main-axis space. The result is the free space.
- It divides the free space among the flexible children in proportion to their
flexvalues, then lays each of them out with the share it received.
Step 1 explains the most common layout error. A fixed-size child never shrinks. If the fixed children are wider than the Row, you get the yellow-and-black overflow stripe.
Expanded and Flexible
Flexible and Expanded are both wrappers that mark a child as flexible. Expanded is a Flexible with fit: FlexFit.tight.
| Widget | Fit | Child's allowed main-axis size |
|---|---|---|
| `Expanded` | `FlexFit.tight` | Exactly its share |
| `Flexible` | `FlexFit.loose` (default) | From 0 up to its share |
The usual use of Expanded is to let one child absorb the remaining space while its neighbours keep their natural size.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(body: SafeArea(child: ProfileRow())),
),
);
class ProfileRow extends StatelessWidget {
const ProfileRow({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const CircleAvatar(child: Icon(Icons.person)),
const SizedBox(width: 12),
const Expanded(
child: Text(
'A very long display name that would otherwise overflow the row',
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 12),
FilledButton(onPressed: () {}, child: const Text('Follow')),
],
),
);
}
}The avatar, the spacers and the button are measured first. The text gets whatever width is left, so it truncates on a phone and shows fully on a wide window. Without Expanded, the Text would be measured at its natural width and the Row would overflow.
Flex factors and loose fits
The flex argument sets the ratio between flexible children. The ratio applies to the free space, not to the total width.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: FlexDemo())));
class FlexDemo extends StatelessWidget {
const FlexDemo({super.key});
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(child: Container(color: Colors.indigo, height: 60)),
Expanded(flex: 2, child: Container(color: Colors.teal, height: 60)),
Flexible(
child: Container(color: Colors.orange, width: 40, height: 60),
),
],
);
}
}The flex values are 1, 2 and 1, so the total is 4. The indigo box gets a quarter of the free space, the teal box gets half, and the orange box is offered a quarter. Because Flexible is loose, the orange box takes only its 40 pixels. The rest of its share stays empty. It is not given to the other children. This is the main practical difference between the two widgets. Use Flexible when the child should shrink to fit but not stretch, such as a chat bubble that grows with its text up to a maximum share.
Spacer is shorthand for Expanded(child: SizedBox.shrink()). It pushes siblings apart in proportion to its flex.
Errors you will meet
| Error message (shortened) | Cause | Fix |
|---|---|---|
| `Incorrect use of ParentDataWidget` | `Expanded` or `Flexible` is not a direct child of a Row, Column or Flex. A `Padding` or `Container` in between breaks it. | Move `Expanded` so it wraps the child directly. |
| `RenderFlex children have non-zero flex but incoming height constraints are unbounded` | A Column with `Expanded` children sits inside a scrollable or another unbounded parent. | Remove `Expanded`, give the Column a fixed height, or use `shrinkWrap` on the list. |
| `RenderFlex overflowed by N pixels` | Non-flexible children are wider than the available space. | Wrap the flexible one in `Expanded`, or switch to `Wrap` (next section). |
The second error follows from the algorithm. Step 2 needs a finite free space. An unbounded main axis has no free space to divide.
Wrap: flowing content onto new lines
A Row never starts a second line. Wrap does. It lays children along the main axis and starts a new run when the next child does not fit. This suits tags, filter chips and button groups whose count or width you do not control.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: TagCloud())));
class TagCloud extends StatelessWidget {
const TagCloud({super.key});
static const _tags = [
'Flutter', 'Dart', 'Layout', 'Responsive', 'Adaptive',
'Widgets', 'Constraints', 'Material 3',
];
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [for (final tag in _tags) Chip(label: Text(tag))],
),
);
}
}The properties to know:
spacingis the gap between children in the same run.runSpacingis the gap between runs.alignmentpositions children within a run along the main axis.runAlignmentpositions the runs within the Wrap along the cross axis.crossAxisAlignmentaligns children of different heights within a run.directiondefaults toAxis.horizontal. UseAxis.verticalfor column-first flow, which needs a bounded height to wrap.
Wrap does not support Expanded or Flexible children. It has no flex algorithm, because a run's length depends on where the break falls. If you need a child to fill the rest of its run, use a Row inside each item instead.
Wrap also lays out every child, so it is not lazy. Use it for tens of items, not thousands. For large collections, use the grid and list builders covered later in this tutorial.
AspectRatio: sizes tied to each other
AspectRatio sizes its child to a width-to-height ratio, which is useful for images, video players and cards. Its algorithm is:
- If the incoming constraints are tight, it has no choice and takes that size. The ratio is ignored.
- Otherwise it tries the largest width the constraints allow and sets the height to
width / aspectRatio. - If that height is too large, it takes the maximum height and derives the width.
- If the width is unbounded, it starts from the height instead.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: VideoCard())));
class VideoCard extends StatelessWidget {
const VideoCard({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
const AspectRatio(
aspectRatio: 16 / 9,
child: ColoredBox(
color: Colors.blueGrey,
child: Center(child: Text('16:9')),
),
),
const Padding(
padding: EdgeInsets.all(12),
child: Text('Caption below the video'),
),
],
);
}
}The Column gives its children the full screen width with unbounded height. AspectRatio takes the full width and computes a height of width * 9 / 16. On a phone this is a short banner. On a wide desktop window the same widget becomes very tall and pushes everything else off screen. That is why you often combine it with a size limit.
import 'package:flutter/material.dart';
class CappedVideo extends StatelessWidget {
const CappedVideo({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 640),
child: const AspectRatio(
aspectRatio: 16 / 9,
child: ColoredBox(color: Colors.blueGrey),
),
),
);
}
}ConstrainedBox caps the width at 640 logical pixels, and AspectRatio derives the height from that. Center loosens the constraints so the box can be narrower than the window.
Choosing between them
- One child should fill the leftover space:
Expanded. - A child should shrink to fit but never exceed its share:
Flexible. - Children should be proportional to each other:
Expandedwith differentflexvalues. - Items should break onto new lines:
Wrap. - A box needs a fixed shape at any width:
AspectRatio, usually with a maximum width.
These widgets adapt continuously to space. They cannot change the structure of the screen, for example turning a Row into a Column or swapping a bottom bar for a rail. That requires reading the window or the local constraints, which the next chapters cover.
Exercise
A Row contains an Icon (24 px wide), a Text with a long label, and a Switch (about 50 px wide), all as direct children. The Row overflows on a narrow phone. Which widget do you wrap the Text in, and why would Flexible also work but behave differently from Expanded when the label is short?
Show answer
Wrap the Text in Expanded. The Icon and Switch are measured first, and the Text then receives all remaining width, so it can wrap or truncate instead of overflowing. Flexible also prevents the overflow, because a long label is constrained to its share. With a short label, Flexible lets the Text keep its natural width, so the Switch sits right after the text. Expanded forces the Text to fill the free space, which pushes the Switch to the far end of the Row.