Flutter GridView – Set crossAxisCount based on Width
To dynamically set crossAxisCount property of GridView based on the device width in Flutter, wrap GridView in LayoutBuilder. LayoutBuilder receives constraints
as parameter for builder. Using constraints.maxWidth
property, we can conditionally set different values for GridView’s crossAxisCount.
Code Snippet
A quick code snippet to set spacing for GridView
via mainAxisSpacing and crossAxisSpacing properties is
return LayoutBuilder(builder: (context, constraints) {
return GridView.count(
crossAxisCount: constraints.maxWidth > 700 ? 4 : 2,
)
};
);
Example
In the following example, we set the crossAxisCount
property with 4
if width is greater than 700
or 2
otherwise.
main.dart
import 'dart:ui';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Tutorial';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
return GridView.count(
primary: false,
crossAxisCount: constraints.maxWidth > 700 ? 4 : 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
padding: const EdgeInsets.all(20),
children: <Widget>[
Container(
padding: const EdgeInsets.all(8),
child: const Text("Tile 1"),
color: Colors.orange[200],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text("Tile 2"),
color: Colors.green[200],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text("Tile 3"),
color: Colors.red[200],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text("Tile 4"),
color: Colors.purple[200],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text("Tile 5"),
color: Colors.blueGrey[200],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text("Tile 6"),
color: Colors.yellow[200],
),
],
);
});
}
}
Screenshot – iPhone Simulator
Screenshot – Chrome (web)
When the width of chrome browser is changed, the GridView dynamically sets the number of items in the cross axis.
Conclusion
In this Flutter Tutorial, we learned how to dynamically set the number of items in the cross axis in GridView, with examples.