GridView Demo in Flutter

By | October 10, 2018

Hi Friends,

Today we will see how to implement GridView in Flutter.

 

 

We are going to use this service for the data
First we will create a Model for the Grid Cell

class HomeCellVO {
  int id;
  String title;
  String icon;

  HomeCellVO({this.id, this.title, this.icon});

  factory HomeCellVO.fromJson(Map<String, dynamic> json) {
    return HomeCellVO(
      id: json['id'] as int,
      title: json['title'] as String,
      icon: json['icon'] as String,
    );
  }
}

No we will create view for Grid Cell

Create a file named “cell.dart” and copy this into it.

import 'package:flutter/material.dart';
import 'home_cell.dart';

class Cell extends StatelessWidget {
  const Cell(this.homeCellVO);
  @required
  final HomeCellVO homeCellVO;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: new Column(
          children: <Widget>[
            Image.network(homeCellVO.icon,
                width: 100.0,
                height: 100.0,
                alignment: Alignment.center,
                fit: BoxFit.cover),
            Text(homeCellVO.title),
          ],
        ),
      ),
    );
  }
}

Service Class

We have the below service class for fetching the data.

service.dart

import 'dart:async';
import 'dart:convert';
import 'home_cell.dart';
import 'constants.dart';
import 'package:http/http.dart' as http;

class Services {
  static Future<List<HomeCellVO>> fetchHomeData() async {
    final response = await http.get(CONSTANTS.HOME_SERVICE_URL);
    if (response.statusCode == 200) {
      List<HomeCellVO> list = parsePostsForHome(response.body);
      return list;
    } else {
      throw Exception(CONSTANTS.INTERNET_ERROR);
    }
  }

  static List<HomeCellVO> parsePostsForHome(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<HomeCellVO>((json) => HomeCellVO.fromJson(json)).toList();
  }
}

To read about the http implementation, please read this post.

Also we have a seperate file for constants called constants.dart

class CONSTANTS {
  static const String INTERNET_ERROR = "No Internet Connection";
  static const HOME_SERVICE_URL = 'http://codemansion.co.in/test.json';
}

Implementation

Now the class that implements the GridView

home.dart

import 'package:flutter/material.dart';

import 'cell.dart';
import 'constants.dart';
import 'home_cell.dart';
import 'services.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<HomeCellVO> homeCells = new List();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        body: Container(
          child: FutureBuilder<List<HomeCellVO>>(
            future: Services.fetchHomeData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return new Padding(
                  padding: new EdgeInsets.all(10.0),
                  child: GridView.builder(
                    itemCount: snapshot.data.length,
                    gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2),
                    itemBuilder: (BuildContext context, int index) {
                      return new GestureDetector(
                        child: Cell(snapshot.data[index]),
                        onTap: () => gridClicked(index),
                      );
                    },
                  ),
                );
              } else if (snapshot.hasError) {
                return Text(CONSTANTS.INTERNET_ERROR);
              }
            },
          ),
        ));
  }
}

gridClicked(int index) {
  print('gridClicked : $index');
}

gridClicked is the function for handling the clicks in the Grid.

Great, we are all done.
Thanks.

Please leave your valuable comments below this post.

All Done

All Done

Leave a Reply

Your email address will not be published. Required fields are marked *