The GridView widget is used to create a scrollable 2D array of widgets.
This is especially useful when displaying a collection of items in a grid format.
There Are Some Common Attributes for GridView
crossAxisCount | umber of columns in the grid |
crossAxisSpacing | Spacing between columns |
mainAxisSpacing: | Spacing between rows |
itemCount | Number of items in the grid |
SliverGridDelegateWithFixedCrossAxisCount | Used to define the grid layout with a fixed number of columns |
Here's a basic example of using GridView in Flutter
File open lib->main.dart file −
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GridView Example'),
),
body: MyApp(),
),
)
);
}
class MyApp extends StatelessWidget {
final titles=[
"Title 1",
"Title 2",
"Title 3",
"Title 4",
"Title 5",
"Title 6",
"Title 7",
"Title 8",
"Title 9",
"Title 10",
"Title 11",
"Title 12"];
final subTitle=[
"This is Sub Title 1",
"This is Sub Title 2",
"This is Sub Title 3",
"This is Sub Title 4",
"This is Sub Title 5",
"This is Sub Title 6",
"This is Sub Title 7",
"This is Sub Title 8",
"This is Sub Title 9",
"This is Sub Title 10",
"This is Sub Title 11",
"This is Sub Title 12",
];
@override
Widget build(BuildContext context) {
return
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,// Number of columns in the grid
crossAxisSpacing: 8.0,// Spacing between columns
mainAxisSpacing: 12.0,// Spacing between rows
childAspectRatio: 1.0 // Ratio of child
),
itemCount: titles.length,
itemBuilder:(BuildContext context,int index){
return Card(
color: Colors.white70,
// alignment: Alignment.center,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(titles[index]),
Text(subTitle[index]),
],
),
);
}
);
}
}
Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.
Output: