Wednesday, August 1, 2018

Flutter - GridView builder example.


In a mobile application, GridView is a view group that displays items in a two-dimensional scrolling grid (rows and columns).  Users can select any grid item by clicking on it. By default GridView scrollable, so we don’t need to use ScrollView or anything else with GridView.

The GridView objects may be a Text and Image or a view group which has both an image and some text. An example of GridView is your default image gallery in mobile. Where you have a number of items displayed using them in a grid manner.

Grid view helps users when they’re examining details. For example, if a user is shopping for a shirt, they’ll have a specific type in mind. It’s only after the user has narrowed down the content to a category that grid view is most effective. But once the user is in the category of shirts they want, the images will have more relevancy. The user can scan the shirts and spot certain details they’re looking for with ease.

To implement grid view in the Flutter application, we have GridView widget. The simplest way to get started using grids is by using the  GridView.count constructor, because it allows us to specify how many rows or columns we’d like.

In this post, we'll hit an API and get the detail of countries and display it in the grid view as you can see the final output below. 



This will help us visualize how GridView works. So, let's start its implementation with the following steps.


Creating a new Project

1. Create a new project from File ⇒ New Flutter Project with your development IDE. 
2. Open main.dart file and edit it. As we have set our theme and change debug banner property of Application.
main.dart
void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'World'; return new MaterialApp( debugShowCheckedModeBanner: false, title: appTitle, theme: new ThemeData( primaryColor: const Color(0xFF02BB9F), primaryColorDark: const Color(0xFF167F67), accentColor: const Color(0xFFFFAD32), ), home: new HomePage(title: appTitle), ); } }

3. Now create HomePage class inside of main.dart as you can below. Here we using Scaffold as a root widget that contains App bar and FutureBuilder. FutureBuilder displays a progress bar until we getting detail of counties from the server.
main.dart
class HomePage extends StatelessWidget { final String title; HomePage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(title, style: new TextStyle( color: const Color(0xFFFFFFFF), ), ), ), body: new FutureBuilder<List<Country>>( future: fetchCountry(new http.Client()), builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? new CountyGridView(country: snapshot.data) : new Center(child: new CircularProgressIndicator()); }, ), ); } }

4. After that create network layer of the application that get list of countries from the server and parse it. As you can see above, we have called  fetchCountry method for it
networklayer.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter_gridview/country.dart'; import 'package:http/http.dart' as http; Future<List<Country>> fetchCountry(http.Client client) async { final response = await client.get('http://restcountries.eu/rest/v2/all'); // Use the compute function to run parsePhotos in a separate isolate return compute(parseData, response.body); } // A function that will convert a response body into a List<Country> List<Country> parseData(String responseBody) { final parsed = json.decode(responseBody).cast<Map<String, dynamic>>(); List<Country> list = parsed.map<Country>((json) => new Country.fromJson(json)).toList(); return list; }

5. For contain details of countries, we have to create a model class Country. We'll use it for parse server response JSON and display grid view items.
country.dart
class Country { String name; String nativeName; String flag; String capital; Country({this.name, this.flag, this.capital,this.nativeName}); factory Country.fromJson(Map<String, dynamic> json) { return new Country( name: json['name'] as String, nativeName: json['nativeName'] as String, flag: json['flag'] as String, capital: json['capital'] as String, ); } }

6. At the end, create gridview.dart class and add GridView in the build method. As you can see below, we have declared the size of gridview items by using List. generate method of GridView.
girdview.dart
@override Widget build(BuildContext context) { return new GridView.count( primary: true, crossAxisCount: 2, childAspectRatio: 0.80, children: List.generate(country.length, (index) { return getStructuredGridCell(country[index]); }), ); }
for the class simplicity, we have created a new method getStructuredGridCell. Here, we passing items by using an index in the method, we using Card widget for display detail.
gridview.dart
Card getStructuredGridCell(Country country) { return new Card( elevation: 1.5, child: new Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, verticalDirection: VerticalDirection.down, children: <Widget>[ new SvgPicture.network( country.flag.replaceAll('https', 'http'), height: 130.0, width: 100.0, placeholderBuilder: (BuildContext context) => new Container( padding: const EdgeInsets.all(60.0), child: const CircularProgressIndicator()), ), new Padding( padding: EdgeInsets.only(left: 10.0), child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text(country.name), new Text(country.nativeName), new Text(country.capital), ], ), ) ], )); }


If you have followed the article carefully, you can see the app running very smoothly as shown in the video demo. But if you facing any problem.



Source Code               Flutter firebse storage apk


You can get the working project on Github and please feel free to ask in the comment section below.


Share:

3 comments:

  1. A very good example. In case, I want to use jpg, or png for picture, how to do that ?

    ReplyDelete
  2. Image.network(
    'https://picsum.photos/250?image=9',
    )

    ReplyDelete
  3. Bro,I need help,I am using grid view builder to load images from friestore, when I scroll down images are again loading,I also tried cached network image but it not worked,how to solve this problem???

    ReplyDelete

We're Social

Categories

Ad here

  • Cover art Blend

    Blend app is very advanced app there are lots of features like shayari, status, chat, feed....