Sub topic 2
Dividers and Gaps with ListView.separated
This chapter assumes you know Dart lists and closures, can write a StatelessWidget, and have used ListView.builder. It covers separators between list items, then grids built with GridView.count, GridView.extent, and GridView.builder.
Adding separators with ListView.separated
ListView.separated builds items the same way ListView.builder does. It also calls separatorBuilder to place a widget between each pair of neighboring items.
ListView.separated(
itemCount: items.length,
itemBuilder: (context, index) => ListTile(title: Text(items[index])),
separatorBuilder: (context, index) => const Divider(height: 1),
)With n items, separatorBuilder runs n - 1 times. The index it receives is the item that comes before the separator.
Quick grids with GridView.count and GridView.extent
GridView.count fixes the number of columns through crossAxisCount. GridView.extent fixes the maximum width of each tile through maxCrossAxisExtent, and the column count follows from that. Both take an explicit list of children, so use them only for short, fixed collections.
GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
padding: const EdgeInsets.all(8),
children: List.generate(
12,
(index) => Card(child: Center(child: Text('$index'))),
),
)Controlling columns with grid delegates
GridView.count and GridView.extent are shortcuts for two grid delegates. A grid delegate decides how many columns exist and how large each tile is. Pass one to gridDelegate when you use GridView.builder.
| Delegate | Sets | Column count changes with screen width |
|---|---|---|
| `SliverGridDelegateWithFixedCrossAxisCount` | Number of columns | No |
| `SliverGridDelegateWithMaxCrossAxisExtent` | Maximum tile width | Yes |
GridView.builder for large grids
GridView.builder creates tiles only when they are needed, so it handles hundreds of items well. The example below fits as many 160-pixel columns as the screen allows.
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')));
},
)Exercise
You have 500 product photos and want a grid where each tile is at most 120 pixels wide. Which constructor and delegate do you use, and why?
Show answer
Use GridView.builder with SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 120). The builder creates tiles lazily, so 500 items stay efficient, and the max-extent delegate adjusts the column count to the screen width.