A Grid From a Builder
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 11 of 33.
A grid of a hundred photos has the same problem as a long list: you cannot write every tile, and building them all at once is slow. GridView.builder builds tiles as they scroll in, like ListView.builder:
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return Image.network(photos[index]);
},
)The long name, SliverGridDelegateWithFixedCrossAxisCount, is the grid's layout: a fixed number of tiles per row. It takes the crossAxisCount and the spacing that GridView.count took directly.
itemCount and itemBuilder work the same as in a list: the builder gets each tile's index, starting at 0.
Challenge
EasyThe calendar shows only the first week of June, written by hand. Replace the GridView.count with a GridView.builder that shows all 30 days, numbered from 1, seven to a row.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: const Text('June')),
body: GridView.count(
padding: const EdgeInsets.all(8),
crossAxisCount: 7,
mainAxisSpacing: 4,
crossAxisSpacing: 4,
children: [
Container(
alignment: Alignment.center,
color: Colors.teal.shade100,
child: const Text('1'),
),
Container(
alignment: Alignment.center,
color: Colors.teal.shade100,
child: const Text('2'),
),
Container(
alignment: Alignment.center,
color: Colors.teal.shade100,
child: const Text('3'),
),
Container(
alignment: Alignment.center,
color: Colors.teal.shade100,
child: const Text('4'),
),
Container(
alignment: Alignment.center,
color: Colors.teal.shade100,
child: const Text('5'),
),
Container(
alignment: Alignment.center,
color: Colors.teal.shade100,
child: const Text('6'),
),
Container(
alignment: Alignment.center,
color: Colors.teal.shade100,
child: const Text('7'),
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lists and Screens
1Scrolling Lists
A List That ScrollsList TilesLeading and TrailingTap a List TileDividers Between Rows6Tabs, Drawers and Swipes
Tabs With a Navigation BarFilled Icons for the Open TabA Side DrawerSwipe to DeleteUndo a SwipePractice on your own: Online Flutter compiler