There are different ways to achieve grid view results in Flutter. Here I will explain three ways to do grid views in Flutter CustomScrollView, GridView and GridView.builder.
First one is using CustomScrollView. CustomScrollView is the most efficient way of doing it. It’s very optimized.
If you have chatting app, then CustomScrollView is the best way to go.
CustomScrollView for Grid
CustomScrollView(
primary: false,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.all(20.0),
sliver: SliverGrid.count(
crossAxisSpacing: 10.0,
crossAxisCount: 2,
children: <Widget>[
const Text('He\'d have you all unravel at the'),
const Text('Heed not the rabble'),
const Text('Sound of screams but the'),
const Text('Who scream'),
const Text('Revolution is coming...'),
const Text('Revolution, they...'),
],
),
),
],
)
To use CustomScrollView, you need to understand slivers and related slivers classes. Check out the link for dedicated CustomScrollView.
You may use the above code snippet anywhere in your code.
GridView.builder for Grid
This is another efficient way of doing it. This is less complicated than the earlier approach.
Container(
padding: EdgeInsets.all(12.0),
child: GridView.builder(
shrinkWrap: true,
physics: ScrollPhysics(),
itemCount: 6,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 40.0,
mainAxisSpacing: 10.0
),
itemBuilder: (BuildContext context, int index){
return Text("I love Flutter");
},
))
See the below result of GridView.builder
Other way using GridView.count
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter GridView Example'),
),
body: GridView.count(
crossAxisCount: 2, // Number of columns
mainAxisSpacing: 10.0, // Spacing between rows
crossAxisSpacing: 10.0, // Spacing between columns
children: <Widget>[
// Add your grid items here
// Example: Container(color: Colors.red),
// Example: Container(color: Colors.blue),
],
),
),
);
}
}