Sub topic 7
Quick grids with GridView.count and GridView.extent
This chapter assumes you can write a StatelessWidget, know how Row, Column and Expanded pass constraints, and have used ListView with a children list. It covers the two shortcut constructors for building a grid from a fixed list of widgets: GridView.count and GridView.extent.
What a GridView is
A GridView is a scrollable that arranges its children in rows and columns. It scrolls along one axis, the main axis, and divides the other axis, the cross axis, into equal-sized slots. In the default vertical grid, the main axis runs down the screen and the cross axis runs across it. Columns split the cross axis. Rows stack along the main axis.
Like ListView, a GridView is built on a viewport. It takes the space its parent gives it and shows only a window onto its content. Everything you learned about bounded height applies here too.
Every GridView needs a grid delegate. The delegate is the object that decides how many tiles fit across the cross axis and how large each tile is. The named constructors in this chapter create a delegate for you:
| Constructor | You choose | Flutter computes |
|---|---|---|
| `GridView.count` | Number of columns (`crossAxisCount`) | Tile width, from the available width |
| `GridView.extent` | Maximum tile width (`maxCrossAxisExtent`) | Number of columns, from the available width |
Both take an explicit list of children, so they build every child up front. They suit short grids such as a settings menu, a photo picker with a dozen items or a category screen. Large or dynamic grids belong with GridView.builder, which a later chapter covers.
GridView.count: a fixed number of columns
Use GridView.count when the column count should stay the same on every screen width. The tile width then changes to fill the space.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: CountDemo()));
class CountDemo extends StatelessWidget {
const CountDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('GridView.count')),
body: GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
padding: const EdgeInsets.all(8),
children: List.generate(
12,
(index) => Card(child: Center(child: Text('$index'))),
),
),
);
}
}The parameters work as follows:
crossAxisCountis the number of columns in a vertical grid. It is required.mainAxisSpacingis the gap between rows in a vertical grid.crossAxisSpacingis the gap between columns in a vertical grid.paddingis space around the whole grid, inside the scroll area. Tiles scroll under it rather than being clipped by it.childrenis the list of tile widgets.
How tile size is computed
Suppose the screen is 400 logical pixels wide, with 8 pixels of padding on each side, three columns and 8 pixels of cross-axis spacing. The usable width is 400 − 16 = 384. Two gaps take 16 more, which leaves 368. Each tile is 368 / 3, about 122.7 pixels wide.
By default each tile is as tall as it is wide. This ratio comes from childAspectRatio, which defaults to 1.0. The ratio is width divided by height, so a value of 2 makes tiles twice as wide as they are tall, and 0.5 makes them twice as tall as wide.
GridView.count(
crossAxisCount: 2,
childAspectRatio: 3 / 2,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
padding: const EdgeInsets.all(12),
children: const [
Card(child: Center(child: Text('Wide tile A'))),
Card(child: Center(child: Text('Wide tile B'))),
Card(child: Center(child: Text('Wide tile C'))),
Card(child: Center(child: Text('Wide tile D'))),
],
)Here each tile is 1.5 times as wide as it is tall.
GridView.extent: a maximum tile width
Use GridView.extent when you want tiles of roughly constant size and are happy for the column count to vary. You supply maxCrossAxisExtent, the largest width a tile may have. Flutter then uses as many columns as it takes to keep every tile at or below that width.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ExtentDemo()));
class ExtentDemo extends StatelessWidget {
const ExtentDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('GridView.extent')),
body: GridView.extent(
maxCrossAxisExtent: 150,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
padding: const EdgeInsets.all(8),
children: List.generate(
20,
(index) => Card(child: Center(child: Text('Tile $index'))),
),
),
);
}
}With a 400-pixel-wide screen and 150 as the maximum, Flutter picks three columns, because two columns would be 200 wide and exceed the limit. Rotate the device to 800 pixels and it picks six. Tiles never grow past 150, but they do shrink slightly so the columns fill the row evenly.
The value is a maximum, not an exact width. A tile is almost never exactly 150 pixels wide. If you need exact widths, the grid is the wrong tool, and a Wrap of fixed-size boxes fits better.
Choosing between count and extent
| Situation | Better choice |
|---|---|
| A menu that should always show two columns | `GridView.count` |
| A gallery that should use extra width on tablets and landscape | `GridView.extent` |
| Tiles must stay near a target size for legibility | `GridView.extent` |
| A layout designed for exactly N columns | `GridView.count` |
Scroll direction
A grid can scroll horizontally. Set scrollDirection: Axis.horizontal. The meaning of the axes swaps: the main axis now runs left to right, and the cross axis runs top to bottom. So crossAxisCount becomes the number of rows, and mainAxisSpacing is the gap between columns.
SizedBox(
height: 220,
child: GridView.count(
scrollDirection: Axis.horizontal,
crossAxisCount: 2,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
padding: const EdgeInsets.all(8),
children: List.generate(
10,
(index) => Card(child: Center(child: Text('$index'))),
),
),
)The SizedBox supplies the height. A horizontal grid is unbounded in width, so it needs its cross-axis size fixed by a parent.
Common errors and edge cases
Unbounded height inside a Column
A vertical GridView placed directly in a Column fails with a "Vertical viewport was given unbounded height" error. The Column gives its children unlimited height, and a scrollable cannot size itself to infinity. The fix is the same as for ListView: wrap the grid in Expanded.
Column(
children: [
const Text('Gallery'),
Expanded(
child: GridView.count(
crossAxisCount: 2,
children: List.generate(
6,
(index) => Card(child: Center(child: Text('$index'))),
),
),
),
],
)shrinkWrap: true also removes the error by sizing the grid to its content. It forces Flutter to measure every child, so use it only for short grids.
Tiles with the wrong shape
If content overflows or leaves large empty areas, the cause is almost always childAspectRatio. Tile height follows from tile width, so a tile holding an image and two lines of text needs a ratio below 1. Check this before adding padding or changing fonts.
Everything is built up front
Because GridView.count and GridView.extent take a children list, every tile is created when the grid is built, whether or not it is visible. For 12 tiles that costs nothing. For hundreds of image tiles it wastes memory and slows the first frame. Switch to GridView.builder, which creates tiles lazily, when the list is long or comes from data that changes.
Spacing is not padding on tiles
mainAxisSpacing and crossAxisSpacing apply only between tiles. They add nothing at the outer edges. Use padding on the grid for the outer margin.
Exercise
A gallery screen uses GridView.extent with maxCrossAxisExtent: 120 on a phone that is 360 logical pixels wide, with no padding and no spacing. How many columns appear, and how wide is each tile? What happens if the user rotates the phone to 720 pixels wide?
Show answer
At 360 pixels, 360 / 120 = 3, so there are three columns of 120 pixels each. At 720 pixels, 720 / 120 = 6, so there are six columns, again 120 pixels wide. The tile size stays at the maximum when the width divides evenly, and the column count changes with the screen.
Exercise
You write Column(children: [Text('Photos'), GridView.count(crossAxisCount: 2, children: tiles)]) and get a "Vertical viewport was given unbounded height" error. Give two fixes and say when you would pick each.
Show answer
Wrap the grid in Expanded, so it gets the height left after the Text. Use this when the grid should fill the rest of the screen and scroll on its own. Alternatively, set shrinkWrap: true so the grid takes only the height its tiles need. Use this only when the grid is short, because it forces every child to be measured.
Exercise
A GridView.count with crossAxisCount: 2 shows tiles that cut off the second line of text. Which property do you change first, and in which direction?
Show answer
Change childAspectRatio. Tile height equals width divided by the ratio, so lowering the ratio below its current value, for example from 1.0 to 0.8, makes the tiles taller and gives the text more room.