Sub topic 7
Grids and lists that adjust their column count
This chapter covers how a collection of items can change its number of columns as the available width changes. It assumes you can build a ListView, know what a LayoutBuilder does, and have the windowSizeFor helper from the breakpoints chapter (it is repeated below so the snippets run). It also assumes you know that a scrollable gets a bounded cross axis and an unbounded main axis from its parent.
Why columns should follow width
A grid with a fixed number of columns, such as two, looks right on a phone. On a 1400-pixel desktop window it produces two huge tiles, and on a narrow split-screen window the tiles may be too small to read. The number of columns should be a result of the width, not a constant.
Flutter gives you three ways to get there:
- Let the grid delegate choose the count from a maximum tile width.
- Choose the count yourself from a breakpoint.
- Switch between a one-column list and a multi-column grid.
Letting Flutter pick the count: MaxCrossAxisExtent
SliverGridDelegateWithMaxCrossAxisExtent is the least code. You state the widest a tile may be, and Flutter works out how many columns are needed.
import 'package:flutter/material.dart';
class PhotoGrid extends StatelessWidget {
const PhotoGrid({super.key});
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
itemCount: 40,
itemBuilder: (context, index) =>
Card(child: Center(child: Text('Item $index'))),
);
}
}The delegate uses this rule:
- Take the cross-axis extent of the scrollable, which is its width minus padding.
- Compute
columns = ceil(extent / (maxCrossAxisExtent + crossAxisSpacing)), with a minimum of 1. - Compute the tile width as
(extent - spacing * (columns - 1)) / columns.
Here is the rule with real numbers. The grid above has 8 pixels of padding on each side and 8 pixels of spacing.
| Window width | Extent after padding | Columns | Tile width |
|---|---|---|---|
| 360 | 344 | 2 | 168 |
| 700 | 684 | 4 | 165 |
| 1200 | 1184 | 6 | 190.4 |
Because of the ceil, tiles are never wider than the maximum. They can be narrower, which is why maxCrossAxisExtent is a ceiling and not a target width. The shorthand GridView.extent(maxCrossAxisExtent: 200, children: [...]) builds the same delegate for a non-lazy grid.
Choosing the count yourself: breakpoints
Sometimes you want to control the count exactly. A dashboard might show 2 columns on phones, 3 on tablets, and 5 on desktop, with no values in between. In that case use SliverGridDelegateWithFixedCrossAxisCount and compute crossAxisCount from a window-size class.
import 'package:flutter/material.dart';
enum WindowSize { compact, medium, expanded }
WindowSize windowSizeFor(double width) {
if (width < 600) return WindowSize.compact;
if (width < 840) return WindowSize.medium;
return WindowSize.expanded;
}
int columnsFor(WindowSize size) => switch (size) {
WindowSize.compact => 2,
WindowSize.medium => 3,
WindowSize.expanded => 5,
};
class BreakpointGrid extends StatelessWidget {
const BreakpointGrid({super.key});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final columns = columnsFor(windowSizeFor(constraints.maxWidth));
return GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
childAspectRatio: 1.2,
),
itemCount: 40,
itemBuilder: (context, index) =>
Card(child: Center(child: Text('Item $index'))),
);
},
);
}
}LayoutBuilder is used here instead of MediaQuery.sizeOf because the grid may sit beside a navigation rail or inside a pane. Its own width is then smaller than the window width, and the column count should follow the width it actually gets.
The two delegates compare as follows:
| Delegate | You specify | Flutter computes | Best for |
|---|---|---|---|
| `WithMaxCrossAxisExtent` | Maximum tile width | Column count and tile width | Galleries and card collections that scale smoothly |
| `WithFixedCrossAxisCount` | Column count | Tile width | Layouts with a designed number of columns per breakpoint |
Controlling tile height
Width is only half of the problem. By default both delegates use childAspectRatio: 1.0, which means the height equals the width. If you set a ratio such as 1.2, the height is the width divided by 1.2, so tile height changes whenever the width changes.
This causes a common failure. A tile that holds text and a button fits at 200 pixels wide. At a larger system font size, or when the tile gets narrower, the content needs more height than the ratio allows, and you see a RenderFlex overflow. There are two ways to avoid it:
- Use
mainAxisExtentto give every tile a fixed height regardless of width. It works with both delegates and replaceschildAspectRatio. This suits tiles that contain text. - Keep
childAspectRatiofor tiles whose content is itself proportional, such as images.
Switching between a list and a grid
On a phone, a single-column list of wide rows is often better than a two-column grid of cramped cards. The list can turn into a grid once there is room.
import 'package:flutter/material.dart';
class ProductList extends StatelessWidget {
const ProductList({super.key, this.count = 60});
final int count;
Widget _tile(BuildContext context, int index) {
return Card(
child: ListTile(
leading: const Icon(Icons.shopping_bag),
title: Text('Product $index'),
subtitle: const Text('In stock'),
),
);
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 600) {
return ListView.builder(
itemCount: count,
itemBuilder: _tile,
);
}
return GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 400,
mainAxisExtent: 88,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
itemCount: count,
itemBuilder: _tile,
);
},
);
}
}The same _tile function builds the items in both branches, so the content stays identical and only the container changes. The 88-pixel mainAxisExtent leaves room for the tile's 72-pixel content plus the card's default margin. Each branch creates its own scroll view, so the scroll position is lost when the width crosses 600. That is acceptable for a window resize, and it rarely matters on a phone. If it matters, use a single CustomScrollView and switch the sliver instead (see the next section).
Slivers and mixed content
A GridView is one scrollable. When a screen has a header followed by a grid, put both in a CustomScrollView and use SliverGrid for the grid part. This keeps one scroll position and lets everything scroll together. A SliverGrid takes the same delegates as GridView, but it has no LayoutBuilder equivalent for box constraints. Use SliverLayoutBuilder and read constraints.crossAxisExtent, which is the width available to the sliver.
Readable widths for lists
A list that stays one column on a wide window creates a different problem: very long rows that are hard to scan. Two fixes work:
- Wrap the list in
AlignandConstrainedBox(constraints: BoxConstraints(maxWidth: 720))to cap the content width and center it. - Switch to a grid once the width passes a breakpoint, as shown above.
Common errors
- "Vertical viewport was given unbounded height." A
GridViewplaced directly inside aColumnhas no height limit. Wrap it inExpanded. UsingshrinkWrap: truealso silences the error, but it forces Flutter to measure every child, which defeats lazy building on long lists. - Reading
MediaQueryfor a nested grid. The grid sizes itself from its parent, not from the window. A column count based on window width is wrong when the grid is in a side pane. - Spacing ignored in the count. With
maxCrossAxisExtent, spacing is part of the calculation. DoublingcrossAxisSpacingcan change the number of columns. - Tile width assumed constant. Images and text inside tiles need to adapt, for example with
AspectRatioorImage.fit, because the width varies continuously withmaxCrossAxisExtent.
Exercise
A GridView has 16 pixels of padding on each side, uses SliverGridDelegateWithMaxCrossAxisExtent with maxCrossAxisExtent 150 and crossAxisSpacing 10, and is 500 logical pixels wide. How many columns does it show, and how wide is each tile?
Show answer
The cross-axis extent is 500 - 32 = 468. Columns = ceil(468 / (150 + 10)) = ceil(2.925) = 3. Tile width = (468 - 10 * 2) / 3 = 448 / 3, about 149.3 pixels, which is under the 150-pixel maximum.
Exercise
Why can a grid tile with childAspectRatio 1.0 that contains a Text and a button overflow when the user increases the system font size, and what property avoids the problem?
Show answer
With a fixed aspect ratio, tile height equals tile width, so it does not grow when the text gets larger. The content needs more height than the tile has and overflows. Setting mainAxisExtent gives a fixed or sufficiently large height independent of width, and it can be chosen with text scaling in mind.