Sub topic 8
Controlling columns with grid delegates
This chapter assumes you know basic Dart, the difference between StatelessWidget and StatefulWidget, and how Row, Column and Expanded lay out children. You should also have met GridView.count and GridView.extent. Here you will learn what a grid delegate is, which two built-in delegates exist, and how each setting changes the layout.
What a grid delegate does
A GridView does not decide the column layout itself. It hands that job to a grid delegate, an object of type SliverGridDelegate. The delegate receives the size of the viewport and returns a layout. That layout says how wide each tile is, how tall it is, and where it sits.
Two delegates cover almost every app:
SliverGridDelegateWithFixedCrossAxisCountuses a fixed number of columns.SliverGridDelegateWithMaxCrossAxisExtentcaps the tile width and lets the column count follow the screen width.
The convenience constructors you already know are shortcuts. GridView.count builds a fixed-count delegate for you. GridView.extent builds a max-extent delegate for you. When you use GridView.builder, you pass the delegate yourself through the gridDelegate argument.
The cross axis is the axis perpendicular to the scroll direction. In a vertical grid, the cross axis is horizontal, so "cross axis count" means the number of columns. The main axis is the scroll direction, so mainAxisSpacing is the gap between rows.
Fixed number of columns
Use SliverGridDelegateWithFixedCrossAxisCount when the design calls for the same number of columns on every screen, such as a three-column photo grid.
import 'package:flutter/material.dart';
class FixedGrid extends StatelessWidget {
const FixedGrid({super.key});
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
childAspectRatio: 1,
),
itemCount: 30,
itemBuilder: (context, index) {
return Card(child: Center(child: Text('$index')));
},
);
}
}The delegate has these settings:
| Setting | Meaning | Default |
|---|---|---|
| `crossAxisCount` | Number of columns in a vertical grid. Required. | none |
| `mainAxisSpacing` | Gap between rows in a vertical grid. | 0 |
| `crossAxisSpacing` | Gap between columns in a vertical grid. | 0 |
| `childAspectRatio` | Tile width divided by tile height. | 1.0 |
| `mainAxisExtent` | Fixed tile height. Overrides `childAspectRatio` when set. | null |
The tile width comes from the viewport. Flutter takes the available cross-axis width, subtracts the total spacing between columns, and divides the rest by crossAxisCount. With a 400-pixel-wide grid, no padding, three columns and 8 pixels of spacing, each tile is (400 − 2 × 8) / 3 = 128 pixels wide.
Columns that adapt to screen width
A fixed count looks fine on a phone and oversized on a tablet. SliverGridDelegateWithMaxCrossAxisExtent solves that. You give it the largest width a tile may have. Flutter then picks the smallest number of columns that keeps every tile at or under that width.
import 'package:flutter/material.dart';
class AdaptiveGrid extends StatelessWidget {
const AdaptiveGrid({super.key});
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 160,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
childAspectRatio: 1,
),
itemCount: 200,
itemBuilder: (context, index) {
return Card(child: Center(child: Text('Tile $index')));
},
);
}
}On a 400-pixel-wide screen this grid shows three columns (each about 128 pixels). On a 700-pixel-wide screen it shows five columns. The tiles are stretched to fill the row, so they are usually narrower than the maximum, not equal to it.
The column count is the width divided by the maximum, rounded up. The chart assumes no padding and no spacing, so the numbers shift slightly when you add them. For 400 pixels, 400 / 160 = 2.5, which rounds up to 3.
Choosing between the two delegates
Pick by asking what should stay constant.
- If the number of columns is part of the design, use the fixed count.
- If the size of a tile is part of the design, such as a thumbnail that should never exceed 160 pixels, use the max extent.
You can also combine the two approaches. Read the screen width with LayoutBuilder or MediaQuery, then choose a crossAxisCount yourself. This helps when you want exact breakpoints, such as two columns on phones and four on tablets.
import 'package:flutter/material.dart';
class BreakpointGrid extends StatelessWidget {
const BreakpointGrid({super.key});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final columns = constraints.maxWidth < 600 ? 2 : 4;
return GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
itemCount: 40,
itemBuilder: (context, index) {
return Card(child: Center(child: Text('Item $index')));
},
);
},
);
}
}Notice that the delegate here is not const, because columns is computed at run time.
Tile shape: aspect ratio versus fixed height
Both delegates size tiles in one of two ways.
- By aspect ratio.
childAspectRatiois width divided by height. A value of 1 gives squares. A value of 2 gives tiles twice as wide as tall. A value of 0.75 gives portrait tiles, which suits product cards. - By fixed height.
mainAxisExtentsets the tile height in logical pixels. The width still comes from the column calculation.
Aspect ratio keeps proportions when the width changes. That is a problem for tiles that contain text. When a max-extent grid goes from three columns to five, tiles get narrower, and so do their heights. Text that fit before can now overflow. A fixed mainAxisExtent keeps the height stable, so the content has a predictable amount of vertical room.
import 'package:flutter/material.dart';
class FixedHeightGrid extends StatelessWidget {
const FixedHeightGrid({super.key});
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: const EdgeInsets.all(12),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
mainAxisExtent: 96,
),
itemCount: 50,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Text('Order number $index, shipped today'),
),
);
},
);
}
}Common errors
- Tiles look squashed or stretched.
childAspectRatiois width over height, not height over width. If you wanted tall tiles, use a value below 1. - Text overflows in a grid tile. The aspect ratio makes tile height depend on width. Use
mainAxisExtent, or shorten the content. - Spacing seems doubled at the edges. Spacing applies only between tiles. Edge space comes from the
paddingargument of theGridView. crossAxisCountof 0 or negative. The delegate asserts that the count is greater than zero. Compute the count withmax(1, ...)when it depends on screen width.- The grid is empty or throws an unbounded-height error. This is a constraint problem, not a delegate problem. Wrap the grid in
Expandedinside aColumn, as covered earlier.
Summary of the decision
| Situation | Delegate or constructor |
|---|---|
| Short grid with a fixed column count | `GridView.count` |
| Short grid with a maximum tile width | `GridView.extent` |
| Large grid, fixed column count | `GridView.builder` with `SliverGridDelegateWithFixedCrossAxisCount` |
| Large grid, responsive column count | `GridView.builder` with `SliverGridDelegateWithMaxCrossAxisExtent` |
| Exact breakpoints per screen size | `LayoutBuilder` plus the fixed-count delegate |
Exercise
A GridView.builder uses SliverGridDelegateWithMaxCrossAxisExtent with maxCrossAxisExtent: 150, no padding and no spacing. How many columns does it show on a viewport 480 logical pixels wide, and how wide is each tile? What would you change if tiles that contain two lines of text overflow vertically when the screen gets wider?
Show answer
480 / 150 = 3.2, rounded up gives 4 columns. Each tile is 480 / 4 = 120 pixels wide. The overflow happens because childAspectRatio ties tile height to tile width, so wider screens mean more columns, narrower tiles and shorter tiles. Set mainAxisExtent to a fixed height that fits the text, such as 96, so the height no longer depends on the column count.
Exercise
Write the gridDelegate argument for a grid that shows two columns when the width is under 600 and four columns otherwise. Which delegate do you use, and why can it not be const?
Show answer
Use SliverGridDelegateWithFixedCrossAxisCount inside a LayoutBuilder, for example crossAxisCount: constraints.maxWidth < 600 ? 2 : 4. It cannot be const because the column count is computed from the constraints at run time, and const requires values known at compile time.