Working with GridView in Flutter

Welcome to askflutter.com, your one-stop guide for learning Flutter! In this tutorial, we will explore GridView, a powerful widget that displays items in a grid layout. Whether you're creating an e-commerce app or an image gallery, GridView is an essential tool in your Flutter development journey.

What is GridView?

GridView is a Flutter widget that arranges its children in a scrollable grid. It is perfect for displaying items in rows and columns, like a gallery of photos, a list of products, or a collection of cards.

Key Features of GridView:

  • Displays items in a grid format.
  • Supports vertical and horizontal scrolling.
  • Automatically adjusts the grid layout for screen sizes and item content.
  • Highly customizable to suit your design needs.

Types of GridView

Flutter provides four main types of GridView widgets:

  1. GridView.count
    • Creates a grid with a fixed number of items per row.
    • Easy to set up for grids with equally spaced items.

Example:

GridView.count(
  crossAxisCount: 2, // Number of columns
  crossAxisSpacing: 10, // Spacing between columns
  mainAxisSpacing: 10, // Spacing between rows
  children: List.generate(6, (index) {
    return Container(
      color: Colors.blue,
      child: Center(
        child: Text(
          'Item $index',
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }),
)

Output

Result: A grid with 2 columns and 6 items.

2.GridView.extent

  • Creates a grid with items having a maximum width.
  • Automatically calculates the number of items per row based on the screen size.

Example:

GridView.extent(
  maxCrossAxisExtent: 150, // Maximum width per item
  crossAxisSpacing: 10,
  mainAxisSpacing: 10,
  children: List.generate(10, (index) {
    return Container(
      color: Colors.green,
      child: Center(
        child: Text(
          'Item $index',
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }),
)

Result: Items fit dynamically based on the screen size, maintaining the maximum width.

3.GridView.builder

  • Dynamically builds items as needed.
  • Ideal for large or infinite data lists.

Example:

GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 3, // Number of columns
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
  ),
  itemCount: 20, // Total items
  itemBuilder: (context, index) {
    return Container(
      color: Colors.orange,
      child: Center(
        child: Text(
          'Item $index',
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  },
)

Result: A grid of 20 items, built dynamically as you scroll.

4.GridView.custom

  • Allows for complete customization.
  • Uses SliverGridDelegate for advanced control over the grid layout.

Example:

GridView.custom(
  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 150,
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
  ),
  childrenDelegate: SliverChildBuilderDelegate(
    (context, index) => Container(
      color: Colors.purple,
      child: Center(
        child: Text(
          'Item $index',
          style: TextStyle(color: Colors.white),
        ),
      ),
    ),
    childCount: 12, // Total items
  ),
)

Result: A fully customized grid layout.

Understanding Grid Delegates

Grid delegates determine how items are placed within the grid.

  1. SliverGridDelegateWithFixedCrossAxisCount

    • Defines a fixed number of items per row.
    • Used in GridView.builder.
    SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 3, // Number of columns
      crossAxisSpacing: 10,
      mainAxisSpacing: 10,
    )
    
    
  2. SliverGridDelegateWithMaxCrossAxisExtent

    Defines a maximum width for items and Used in GridView.custom.

    SliverGridDelegateWithMaxCrossAxisExtent(
      maxCrossAxisExtent: 150, // Maximum width
      crossAxisSpacing: 10,
      mainAxisSpacing: 10,
    )
    

When to Use Which GridView?

  • GridView.count: When you know the fixed number of columns.
  • GridView.extent: When you want to control item width based on the screen.
  • GridView.builder: For large, scrollable datasets (e.g., API data).
  • GridView.custom: For advanced layouts requiring full customization.

Tips for Working with GridView

  • Responsive Design: Use MediaQuery to adapt the grid layout to different screen sizes.
  • Performance: Use GridView.builder for large datasets to avoid memory issues.
  • Spacing and Padding: Add crossAxisSpacing, mainAxisSpacing, and padding for better UI.
  • Dynamic Item Heights: Use mainAxisExtent for consistent row heights.

Common Use Cases

Image Gallery Example

GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 3,
    crossAxisSpacing: 5,
    mainAxisSpacing: 5,
  ),
  itemCount: imageUrls.length,
  itemBuilder: (context, index) {
    return Image.network(imageUrls[index]);
  },
)

Product Grid Example

GridView.builder(
  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 200,
    childAspectRatio: 0.7,
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
  ),
  itemCount: products.length,
  itemBuilder: (context, index) {
    return Card(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Image.network(products[index].image),
          Text(products[index].name),
          Text('\$${products[index].price}'),
        ],
      ),
    );
  },
)

Conclusion

GridView is a versatile and powerful widget that lets you build stunning grid-based layouts with ease. By understanding the different types of GridView and their use cases, you can create responsive and visually appealing designs for your Flutter apps.

Happy coding, and stay tuned for more beginner-friendly tutorials on askflutter.com! 🚀