Sub topic 9
GridView.builder for large grids
This chapter assumes you know the ListView.builder pattern, StatelessWidget and StatefulWidget, and how Expanded works inside a Column. Here you will build large grids that create only the tiles on screen, choose between the two common grid delegates, and avoid the mistakes that make a grid slow or break its layout.
Why a builder for grids
GridView.count and GridView.extent take a complete children list. Every child widget exists before the first frame, even if the user never scrolls to it. That is fine for a dozen tiles. For a photo gallery or product catalog with hundreds or thousands of entries, it wastes memory and slows startup.
GridView.builder works like ListView.builder. You give it an item count and a function that builds one tile for an index. The grid calls that function only for tiles that are visible or close to the viewport. Tiles that scroll far away are discarded, and the function runs again if the user scrolls back.
The three required ideas
A GridView.builder needs three arguments in practice:
gridDelegatedecides how many columns there are and how big each tile is.itemCountsays how many tiles exist.itemBuilderis called as(BuildContext context, int index)and returns the widget for that index.
Here is a complete app you can run:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ColorGrid()));
class ColorGrid extends StatelessWidget {
const ColorGrid({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('1000 tiles')),
body: GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 160,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
childAspectRatio: 1,
),
itemCount: 1000,
itemBuilder: (context, index) {
final color = Colors.primaries[index % Colors.primaries.length];
return DecoratedBox(
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: Center(
child: Text(
'$index',
style: const TextStyle(color: Colors.white, fontSize: 20),
),
),
);
},
),
);
}
}The Scaffold body gives the grid a bounded height, so no extra wrapper is needed.
Choosing a grid delegate
The delegate is the main decision in a grid. Flutter provides two.
| Delegate | You specify | Result |
|---|---|---|
| `SliverGridDelegateWithFixedCrossAxisCount` | `crossAxisCount` | Always the same number of columns. Tile width changes with screen width. |
| `SliverGridDelegateWithMaxCrossAxisExtent` | `maxCrossAxisExtent` | Tile width stays at or below the maximum. Column count changes with screen width. |
Use the fixed count when the design requires it, such as a three-column photo grid that mimics a gallery app. Use the max extent when the app runs on phones, tablets, and resizable windows. A phone in portrait might get two columns and a tablet might get six, without any code that checks the screen size.
With the max extent delegate, Flutter picks the smallest column count where every tile fits under the maximum, then divides the width evenly. A maxCrossAxisExtent of 160 on a 400-pixel-wide grid with no spacing gives three columns of about 133 pixels, not two columns of 160. Tiles are usually narrower than the maximum, so don't expect exactly 160.
Spacing and padding
mainAxisSpacing is the gap between rows in a vertical grid. crossAxisSpacing is the gap between columns. The padding argument on the grid adds space around the whole content and scrolls with it. The padding is taken off the available width before columns are calculated.
Controlling tile shape
Both delegates have two ways to set tile height.
childAspectRatiois the tile's width divided by its height. A value of1gives squares. A value of0.75gives tiles taller than they are wide, like a portrait photo. The default is1.mainAxisExtentis a fixed height in logical pixels. When you set it,childAspectRatiois ignored.
Aspect ratios have a catch. The tile height changes with the tile width, so on a narrow screen with a fixed ratio, text inside a tile may no longer fit and overflow. When a tile holds an image plus text, a fixed height is often safer:
GridView.builder(
padding: const EdgeInsets.all(12),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
mainAxisExtent: 220,
),
itemCount: 40,
itemBuilder: (context, index) {
return Card(
clipBehavior: Clip.antiAlias,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ColoredBox(
color: Colors.primaries[index % Colors.primaries.length],
),
),
Padding(
padding: const EdgeInsets.all(8),
child: Text('Product $index', maxLines: 1),
),
],
),
);
},
)Each tile is forced to a fixed 220 pixels high. The Expanded inside the card takes whatever space the text leaves. The text sets its own height, so the layout holds at any width.
How lazy building works
Each time the scroll position changes, the viewport works out which part of the grid is visible. It asks the delegate where each tile goes, then calls itemBuilder for the indices in that range plus a small margin beyond the edges. Tiles that leave that range are disposed.
The last box matters. If a tile is a StatefulWidget, its state is destroyed when it scrolls away. A checkbox the user ticked will come back unticked unless you store its value outside the tile, for example in a list or a state management object. Keep selection and similar data in the parent, and pass it down by index.
Edge cases and common errors
Unbounded height
Like any scrollable, a grid needs a finite height in its scroll direction. Placing a GridView.builder directly inside a Column throws a "Vertical viewport was given unbounded height" error. Wrap it in Expanded:
Column(
children: [
const Text('Gallery'),
Expanded(
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: 300,
itemBuilder: (context, index) => Card(child: Center(child: Text('$index'))),
),
),
],
)shrinkWrap removes the benefit
Setting shrinkWrap: true also removes the unbounded error, because the grid sizes itself to its content. To do that, Flutter must measure every child, so it builds all of them. For a large grid this brings back the cost you chose the builder to avoid. Use shrinkWrap only for small grids. For a big grid inside a larger scrolling page, use CustomScrollView with SliverGrid, which a later chapter covers.
Item count and indexes
itemCountcaps the indices.itemBuilderis never called with an index at or above it, so you don't need to guard against going past the end of a list of that length.- If you omit
itemCount, the grid asks for tiles untilitemBuilderreturnsnull. Returningnullmarks the end. Without that, the grid never ends. This is useful for feeds, but you must stop it yourself. - If the underlying list changes length, update
itemCountin the samesetStatecall. A stale count causes aRangeErrorwhen you index into the list.
Cost of each tile
itemBuilder runs during scrolling, so keep it light. Don't do parsing, sorting, or network calls inside it. Prepare the data beforehand and only create widgets in the builder. Mark parts of a tile const where possible. When tiles show network images, set a cacheWidth or cacheHeight on the image so Flutter decodes a small version instead of a full-size photo for each tile.
Reordering and keys
If items can be inserted, removed, or sorted, tiles that keep state need keys so Flutter pairs state with the right item. Give each tile a ValueKey of its item id. The builder also accepts a findChildIndexCallback that maps a key back to an index, which lets Flutter keep tile state across reorders. For a grid of stateless tiles you can skip this.
Putting it together
When you pick a grid for a data set, check these in order:
- Is the item count large or unknown? Use
GridView.builder. - Must the column count never change? Use the fixed count delegate. Otherwise use max extent.
- Does tile content have variable text height? Use
mainAxisExtent. Otherwise usechildAspectRatio. - Is the grid inside a
Column? Wrap it inExpanded.
Exercise
A grid uses SliverGridDelegateWithMaxCrossAxisExtent with maxCrossAxisExtent: 200 and no spacing or padding. How many columns does it show on a screen 500 logical pixels wide, and how wide is each tile? Then explain why adding shrinkWrap: true to fix a "Vertical viewport was given unbounded height" error is a poor choice for a 5000-item grid.
Show answer
The grid needs the smallest column count where each tile is at most 200 wide. Two columns would be 250 wide, which is too big. Three columns give about 166.7 pixels each, so it shows 3 columns of roughly 166.7 pixels. shrinkWrap: true makes the grid size itself to all of its content, so Flutter builds and lays out all 5000 tiles up front and the lazy building is lost. The better fix is to wrap the grid in Expanded, or to give it another bounded height.