Guide on implementing GridView in Flutter

In this guide, we will discuss how to implement a GridView in a flutter. What shall we do today is to show the list of fruit using GridView.builder. At first, we should know what is GridView in flutter is.

GridView is a widget that displays a list of items as a 2D array. In simple terms, the items are shown in a table format. Unlike a normal list, in which items are rendered only in one direction, GridView renders items both horizontally and vertically. As the name suggests, a GridView Widget is used when we have to display something on a Grid. We can display images, text, icons, etc on GridView.

Basically we can implement GridView in various ways in Flutter Some of them are given below :

  • GridView.count()
  • GridView.builder()
  • GridView.custom()
  • GridView.extent()

we can show a list with a fixed number of items by using the GridView.count(). This constructor enables you to create a GridView with a fixed number of items. It also simplifies the method of specifying the number of items on the cross-axis. The Sample of the Code look like a

GridView.count(
  crossAxisCount: 3,
  children: [
    ...
  ],
)

The number of items to show on the cross-axis is assigned to the crossAxisCount property. If we look carefully, we will notice that we don’t need to silverGridDelegateWithFixedCrossAxisCount() anymore.

In the above implementation of the grid view, There are Similar properties of all of them, but we will focus only on the GridView.builder.

There are various properties of the GridView.builder some of them are given below

crossAxisCount specify the number of columns in a grid view.
crossAxisSpacing specify the number of pixels between each child widget listed on the cross axis.
mainAxisSpacing specify the number of pixels between each child widget listed on the main axis.
padding:specify the space around the whole list of widgets.
scrollDirectionspecify the direction in which the items on GridView scroll. By default, it scrolls in a vertical direction.
reverseIf it is true, it will reverse the list in the opposite direction along the main axis
physics determine how the list behaves when the user reaches the end or the start of the widget while scrolling.
shrinkWrapSetting the shrinkWrap value to true causes GridView to take only the required space to fill items in the scroll direction. This defaults to false and reserves the entire screen even if the items are not in the list
primary If true, its ‘Scroll Controller’ is obtained implicitly by the framework.
scroll direction: It defines the direction in which the items on GridView will move, by default it is vertical.
itemCount: define the amount of data to be displayed.
gridDelegate determines the grid or its divider. Its argument should not be null. It is a property that controls how items are shown in a list
itemBuilder create items that will be displayed on the grid view. It will be called only when the indices >= zero && indices < itemCount.

Let’s take an example of how we can implement the Gridview. builder() in our flutter application.

we will create a new model name Fruit that includes the String of name description and the URL of that class name Fruit and store it into a new file inside the lib folder name fruit_model.dart.

class Fruit {
  String name, desc, url;
  Friut({
    required this.name,
    required this.desc,
    required this.url,
  });
}

Now we will again create a new file name as fruit_data.dart that includes the dummy data.

import 'package:vlogpost/model/student.dart';

List<Friut> friuts= [
  Friut(
      name: 'Apple',
      desc:
          'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the',
      url:
          'assets/apple.jpg'),
  Friut(
      name: 'Banana',
      desc:
          'banana is an elongated, edible fruit - botanically a berry - produced by several kinds of large herbaceous flowering plants in the genus Musa.',
      url:
          'assets/banana.jpg'),
  Friut(
      name: 'Grape',
      desc:
          'The grapefruit (Citrus × paradisi) is a subtropical citrus tree known for its relatively large, sour to semi-sweet, somewhat bitter fruit.',
      url:
          'assets/grape.jpg'),
  Friut(
      name: 'Mango',
      desc:
          'A mango is an edible stone fruit produced by the tropical tree Mangifera indica which is believed to have originated from the region between northwestern ...',
      url:
          'assets/mango.jpg'),
  Friut(
      name: 'Orange',
      desc:
          'An orange is a fruit of various citrus species in the family Rutaceae ); it primarily refers to Citrus × sinensis, which is also called sweet orange',
      url:
          'assets/orange.jpg'),
  Friut(
      name: 'WaterMelon',
      desc:
          'Watermelon is grown in favorable climates from tropical to temperate regions worldwide for its large edible fruit',
      url:
          'assets/watermelon.jpg'),
  Friut(
      name: 'Papaya',
      desc:
          'Papayas grow in tropical climates and are also known as papaws or pawpaws. Their sweet taste, vibrant color, and the wide variety of health benefits they ',
      url:
          'assets/papaya.jpg'),
  Friut(
      name: 'Coconut',
      desc:
          'A coconut is the edible fruit of the coconut palm (Cocos nucifera), a tree of the palm family. ',
      url:
          'assets/coconut.jpg'),
  
];

In the above line of code, I have used the local image name as an assets folder to store the image of fruits. for these, I have taken different fruit images which are shown below.

The Next Step is to include the assets folder inside the pubspec. yaml which is shown below

# To add assets to your application, add an assets section, like this:
  assets:
    - assets/

Now let’s implement the code in the Flutter application.

import 'package:flutter/material.dart';
import 'package:vlogpost/data/food_data.dart';
import 'package:vlogpost/model/student.dart';
import 'package:vlogpost/screen/gridview_detail_screen.dart';

class GridViewScreen extends StatefulWidget {
  const GridViewScreen({Key? key}) : super(key: key);

  @override
  State<GridViewScreen> createState() => _GridViewScreenState();
}

class _GridViewScreenState extends State<GridViewScreen> {
  List<Friut> fruit= [];

  @override
  void initState() {
    fruit= List.of(foods);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GridView in Flutter'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          GridView.builder(
              shrinkWrap: true,
              itemCount: food.length,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 4.0,
                  mainAxisSpacing: 4.0),
              itemBuilder: (context, index) {
                final dataFriut = fruit[index];
                return showListTileGrid(dataFriut);
              })
        ],
      ),
    );
  }

  Widget showListTileGrid(Friut fruit) => Card(
        child: Column(
          children: [
            Expanded(
              child: InkWell(
                onTap: (){
               Navigator.push(context, MaterialPageRoute(builder: (_)=>  GridViewDetailScreen(food: food,)));
                },
                child: Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(15),
                      image: DecorationImage(image: AssetImage(fruit.url))),
                ),
              ),
            ),
            Text(fruit.name)
          ],
        ),
      );
}

On Navigating to its details screen the code is shown below

import 'package:flutter/material.dart';
import 'package:vlogpost/model/student.dart';

class GridViewDetailScreen extends StatefulWidget {
  const GridViewDetailScreen({
    Key? key,
    required this.food,
  }) : super(key: key);

  final Friut fruit;
  @override
  State<GridViewDetailScreen> createState() => _GridViewDetailScreenState();
}

class _GridViewDetailScreenState extends State<GridViewDetailScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.fruit.name),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                widget.fruit.desc,
                style: const TextStyle(
                  color: Colors.black,
                  fontSize: 20,
                ),
                textAlign: TextAlign.justify,
              ),
            )
          ],
        ),
      ),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thanks for reading. Also read: Slivers And CustomScrollView In Flutter