What is GridView in Flutter: Explanation and Example
GridView in Flutter is a widget that displays items in a scrollable grid layout with rows and columns. It helps arrange multiple widgets in a neat grid, similar to tiles on a wall or photos in an album.How It Works
GridView arranges child widgets in a grid pattern, automatically creating rows and columns based on the available space and configuration. Imagine a photo gallery app where pictures are shown in rows and columns; GridView helps build that layout easily.
It scrolls vertically or horizontally if the content is larger than the screen, so users can swipe to see more items. You can control the number of columns or the size of each grid cell, making it flexible for different designs.
Example
This example shows a simple GridView with 6 colored boxes arranged in 2 columns.
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('GridView Example')), body: GridView.count( crossAxisCount: 2, children: List.generate(6, (index) { return Container( margin: EdgeInsets.all(8), color: Colors.blue[(index + 1) * 100], child: Center( child: Text('Box ${index + 1}', style: TextStyle(color: Colors.white, fontSize: 18)), ), ); }), ), ), ); } }
When to Use
Use GridView when you want to display multiple items in a grid layout, such as photo galleries, product lists, or dashboards. It is perfect when you want to show many similar items in a compact and organized way.
For example, an e-commerce app can use GridView to show products in rows and columns, making it easy for users to browse many items quickly.
Key Points
- GridView arranges widgets in rows and columns.
- It supports scrolling when content is larger than the screen.
- You can control the number of columns or the size of grid cells.
- Useful for photo galleries, product lists, and dashboards.
Key Takeaways
GridView displays widgets in a scrollable grid layout with rows and columns.