Grid View
What is GridView?
GridView is a scrollable widget in Flutter that displays children in a 2D grid format (rows and
columns). It’s commonly used for layouts where items need to be displayed side-by-side, such
as:
Image galleries
Student or user cards
Product listings
Icon menus
Example:
1. Define a List of Colors
final List<Color> colors = [
Colors.red,
Colors.green,
Colors.blue,
Colors.orange,
Colors.purple,
Colors.teal,
];
A list of 6 colors that will be used as background colors for each grid item.
� 2. GridView.builder
child: GridView.builder(
GridView.builder is used for dynamically building grid items on demand for better
performance.
3. Number of Grid Items
itemCount: colors.length,
Tells the grid to generate as many items as there are in the colors list (6 items).
4. Grid Layout Configuration
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
childAspectRatio: 1,
),
Defines how the grid items are arranged:
o crossAxisCount: 2 → 2 items per row (2 columns).
o crossAxisSpacing: 10.0 → 10 pixels of space horizontally between columns.
o mainAxisSpacing: 10.0 → 10 pixels of space vertically between rows.
o childAspectRatio: 1 → Each item is square (width : height = 1 : 1).
11. Build Each Grid Item
itemBuilder: (context, index) {
A function that builds each individual grid item based on the index.
12. Colored Container
return Container(
color: colors[index],
Creates a colored Container for each grid tile using the color from the colors list.
📝 13. Centered Text Inside Container
child: Center(
child: Text(
'Item ${index + 1}',
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
);
Places a Text widget inside the container, centered both horizontally and vertically.
Displays text like "Item 1", "Item 2", ..., "Item 6".
Text is white with font size 18.