A Grid of Tiles
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 10 of 33.
A photo gallery or an app's home screen shows things side by side in rows, not in one long column. GridView.count lays its children out in a grid and scrolls like a list:
GridView.count(
crossAxisCount: 2,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
children: [
Container(color: Colors.red),
Container(color: Colors.blue),
Container(color: Colors.green),
],
)crossAxisCount is how many tiles go in each row. The tiles fill the rows from left to right, then start a new row. Each tile is a square, and the tiles of a row share its width.
mainAxisSpacing is the space between the rows and crossAxisSpacing the space between the tiles in a row.
Challenge
EasyThe six colors are stacked in a ListView, one per row. Show them in a grid with two tiles per row instead: a GridView.count with crossAxisCount: 2. Keep 8 pixels of spacing between the tiles.
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('Colors')),
body: ListView(
padding: const EdgeInsets.all(8),
children: [
Container(
color: Colors.red,
alignment: Alignment.center,
child: const Text('Red'),
),
Container(
color: Colors.orange,
alignment: Alignment.center,
child: const Text('Orange'),
),
Container(
color: Colors.yellow,
alignment: Alignment.center,
child: const Text('Yellow'),
),
Container(
color: Colors.green,
alignment: Alignment.center,
child: const Text('Green'),
),
Container(
color: Colors.blue,
alignment: Alignment.center,
child: const Text('Blue'),
),
Container(
color: Colors.purple,
alignment: Alignment.center,
child: const Text('Purple'),
),
],
),
),
);
}
}
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