Sub topic 14
When Row and Column are not enough: Wrap and scrolling
This chapter covers what to do when a Row or Column runs out of room: wrap children onto new lines with Wrap, or let the content scroll. It assumes you know how constraints flow down and sizes flow up. It also assumes you can read a RenderFlex overflowed error and know what Expanded does. If any of that is unfamiliar, review the earlier chapters on constraints, overflow, and flexible children first.
Why Row and Column eventually fail
A Row or Column lays out its children in a single line. It never wraps and never scrolls. The main axis has a fixed size, and the children must fit in it. If they don't fit, Flutter paints the yellow and black overflow stripes in debug mode and prints a RenderFlex overflowed error.
You already know one fix: wrap a child in Expanded or Flexible so it shrinks to fit. That works when one child can give up space. It fails when the children are fixed-size and there are simply too many of them, such as a set of tags, filter chips, or a list of unknown length. For those cases you have two tools:
Wrapwhen the content should flow onto more lines but the page itself does not need to scroll.- A scrollable widget when the content can grow without limit.
The table summarizes the choice.
| Situation | Tool |
|---|---|
| A few fixed-size items that may not fit on one line | `Wrap` |
| Many items, or an unknown number, in one direction | `ListView` |
| A mix of widgets that is taller than the screen | `SingleChildScrollView` |
| A grid of equal tiles | `GridView` |
| A scrolling page with several different sections | `CustomScrollView` with slivers |
Wrap: a Row that starts a new line
Wrap places children along a main axis like a Row does. When the next child would not fit, it starts a new run, which is a new line across the cross axis. Wrap defaults to direction: Axis.horizontal, so by default it behaves like a Row that wraps down.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: TagDemo()));
class TagDemo extends StatelessWidget {
const TagDemo({super.key});
@override
Widget build(BuildContext context) {
const tags = ['Dart', 'Flutter', 'Layout', 'Widgets', 'Constraints', 'Stack', 'Row', 'Column'];
return Scaffold(
appBar: AppBar(title: const Text('Tags')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final tag in tags) Chip(label: Text(tag)),
],
),
),
);
}
}Two spacing properties replace the SizedBox gaps you would add by hand in a Row:
spacingis the gap between children within one run, along the main axis.runSpacingis the gap between runs, along the cross axis.
Narrow the window and the chips reflow onto more lines. A Row of the same chips would overflow.
Alignment in a Wrap
Wrap has three alignment properties. They are easy to confuse because the names look alike.
| Property | What it aligns |
|---|---|
| `alignment` | Children within each run, along the main axis |
| `runAlignment` | The runs themselves, along the cross axis, inside the Wrap's own size |
| `crossAxisAlignment` | Children within a run, along the cross axis (matters when children have different heights) |
runAlignment only has a visible effect if the Wrap is taller than its runs need. That happens when the parent gives it a tight height, for example inside a SizedBox(height: 300). In a Wrap with a loose, unbounded height, the Wrap is exactly as tall as its runs, so there is nothing to align.
SizedBox(
height: 200,
width: double.infinity,
child: Wrap(
spacing: 8,
runSpacing: 8,
alignment: WrapAlignment.center,
runAlignment: WrapAlignment.center,
children: [
for (var i = 1; i <= 6; i++) Chip(label: Text('Item $i')),
],
),
)Constraints and Wrap
Wrap needs a bounded size along its main axis. It uses the incoming maximum width to decide where a run ends. If you put a horizontal Wrap directly inside a horizontal Row without Expanded, the Row passes unbounded width, so the Wrap never breaks a line. It lays everything out on one line and overflows, just like the Row did.
// Wrong: the Row gives the Wrap unbounded width, so it never wraps.
Row(
children: [
Wrap(children: [/* many chips */]),
],
)
// Right: Expanded gives the Wrap a bounded width.
Row(
children: [
Expanded(
child: Wrap(children: [/* many chips */]),
),
],
)This is the same unbounded-constraint rule from the overflow chapter, applied to a new widget.
Wrap is not lazy
Wrap builds all of its children up front. That is fine for dozens of chips and a poor choice for thousands of items. For long collections use a lazily built list or grid, as described next.
Scrolling: when content is longer than the screen
A scrollable widget gives its content unbounded space along the scroll direction and clips the result to a viewport. The viewport itself takes whatever bounded size its parent allows. This is why a ListView has trouble inside a Column: the Column passes unbounded height, and the ListView needs a bounded viewport height. The fix, shown in an earlier chapter, is Expanded.
SingleChildScrollView
SingleChildScrollView makes one child scrollable. It is the quickest fix for a Column that overflows by a modest, known amount, such as a form on a small screen or with the keyboard open.
import 'package:flutter/material.dart';
class SignUpForm extends StatelessWidget {
const SignUpForm({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign up')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final label in ['Name', 'Email', 'Password', 'Confirm password', 'Phone'])
Padding(
padding: const EdgeInsets.only(bottom: 16),
child: TextField(decoration: InputDecoration(labelText: label)),
),
FilledButton(onPressed: () {}, child: const Text('Create account')),
],
),
),
);
}
}The Column inside is laid out with unbounded height, so it takes its natural height. If the content is shorter than the screen, it does not stretch to fill it. Because the Column has an unbounded main axis, Expanded and Spacer inside it will throw an error. There is no leftover space to divide.
SingleChildScrollView builds its whole child at once. Use it for content of modest size, not for long lists.
ListView
ListView is the default choice for a vertical list. It has two forms that matter here.
| Constructor | Children built | Use when |
|---|---|---|
| `ListView(children: [...])` | All at once | A short, fixed list |
| `ListView.builder(itemCount:, itemBuilder:)` | Only those near the viewport | Long or unknown-length lists |
| `ListView.separated(...)` | Only those near the viewport, plus a separator between items | Lists that need dividers |
import 'package:flutter/material.dart';
class MessageList extends StatelessWidget {
const MessageList({super.key, required this.messages});
final List<String> messages;
@override
Widget build(BuildContext context) {
return ListView.separated(
itemCount: messages.length,
separatorBuilder: (context, index) => const Divider(height: 1),
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(child: Text('${index + 1}')),
title: Text(messages[index]),
),
);
}
}Set scrollDirection: Axis.horizontal for a horizontal list. A horizontal ListView inside a Column still needs a bounded height, so give it a SizedBox(height: ...). Expanded would fill the vertical space instead.
GridView
GridView arranges equal tiles in rows and columns and scrolls. GridView.count fixes the number of columns, and GridView.extent fixes the maximum tile width.
GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
padding: const EdgeInsets.all(8),
children: [
for (var i = 0; i < 12; i++)
ColoredBox(
color: Colors.primaries[i % Colors.primaries.length],
child: Center(child: Text('$i')),
),
],
)For long grids, use GridView.builder with a SliverGridDelegateWithFixedCrossAxisCount or SliverGridDelegateWithMaxCrossAxisExtent. Use Wrap instead of GridView when tiles differ in size.
Shrink-wrapping and nested scrollables
Two common mistakes come from putting one scrollable inside another.
- A
ListViewinside aColumnwithoutExpandedthrowsVertical viewport was given unbounded height. - A
ListViewinside aSingleChildScrollViewthrows the same error, for the same reason.
The shrinkWrap: true property makes a ListView size itself to its children, which removes the error. It has a cost: the list must measure every child, so it loses the benefit of lazy building. Combined with NeverScrollableScrollPhysics, it is acceptable for a short list embedded in a larger scrolling page. For long lists it is slow.
The better design is a single scrollable that holds everything. CustomScrollView takes slivers, which are scrollable pieces that share one scroll position.
import 'package:flutter/material.dart';
class MixedPage extends StatelessWidget {
const MixedPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
const SliverAppBar(title: Text('Mixed page'), pinned: true),
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(16),
child: Text('A header that scrolls with the list.'),
),
),
SliverList.builder(
itemCount: 50,
itemBuilder: (context, index) => ListTile(title: Text('Row $index')),
),
],
),
);
}
}SliverToBoxAdapter embeds an ordinary widget in the sliver list. SliverList.builder builds rows lazily. The result is one scroll position, lazy building, and no unbounded-height error.
Choosing between them
Common errors
| Error message | Cause | Fix |
|---|---|---|
| `A RenderFlex overflowed by N pixels` | Fixed-size children exceed the main axis | Use `Wrap`, `Expanded`, or a scroll view |
| `Vertical viewport was given unbounded height` | A scrollable sits in a `Column` or another vertical scrollable | `Expanded`, a `SizedBox` height, or one `CustomScrollView` |
| `RenderFlex children have non-zero flex but incoming height constraints are unbounded` | `Expanded` or `Spacer` inside a scroll view's child | Remove the flex widget or give the `Column` a fixed height |
| A `Wrap` that never breaks lines | The `Wrap` has unbounded width, often inside a `Row` | Wrap it in `Expanded` |
Trade-offs to remember
Wrapmeasures all children each layout pass. It is cheap for dozens of items.SingleChildScrollViewalso builds everything, so it is for modest content.ListView.builderandGridView.builderbuild only visible items. They need a bounded viewport and know their item count or builder.- Scrollables clip their content. Shadows and overflow outside the viewport are cut off unless you set
clipBehavior.
Exercise
A screen has a Column containing a Text header and a ListView of 500 items. The app throws "Vertical viewport was given unbounded height". Explain the cause and give two fixes, saying which one you prefer if the header should scroll away with the list.
Show answer
The Column passes unbounded height to its children, but a ListView needs a bounded height for its viewport. Fix 1: wrap the ListView in Expanded, so the header stays fixed and the list fills the remaining height. Fix 2: replace the Column and ListView with a CustomScrollView, using SliverToBoxAdapter for the header and SliverList.builder for the items. If the header should scroll away with the list, prefer the CustomScrollView, because it has one scroll position and still builds items lazily. Using shrinkWrap: true would also remove the error, but it forces all 500 items to be measured.
Exercise
You place a Wrap of 20 Chip widgets inside a Row, next to an Icon. The chips run off the right edge on a narrow phone instead of wrapping. What change fixes it, and why does it work?
Show answer
Wrap the Wrap in Expanded. A Row gives its non-flex children unbounded width, so the Wrap sees no maximum width and never starts a new run. Expanded gives it a bounded width equal to the Row's remaining space, so the Wrap breaks lines when the chips reach that width.