Wednesday, June 6, 2018

Flutter - ListView Flutter example.

Whenever you need to display a group of related items in the vertical or horizontal direction in mobile. We always need a ListView to display it. Display a specific list is essential almost every app that queries a set of data and returns a list of results, so many apps need to do this at one point or another.

For instance, a list of news items, a list of recipes. It helps you in displaying the data in the form of a scrollable list. Users can then select any list item by clicking on it. 

By working through this tutorial, you’ll become familiar with ListView in Flutter and you will be able to fetch data from the server. You can see the final output of the project below.

                                             


Let's start its implementation with the following steps.

1. First of all, open main.dart file and create the base of Application. Add application app bar and use builder param. Builder param shows a progress indicator until network fetching result from the server.

main.dart build method
@override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(title), ), body: new FutureBuilder<List<Country>>( future: fetchCountry(new http.Client()), builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? new CountyList(country: snapshot.data) : new Center(child: new CircularProgressIndicator()); }, ), ); }

2. For fetch data from the server, we have to add HTTP dependency.



after that create networklayer.dart file. We use it to get data from the server. As you can bellow, we using client.get('API URL') method. It will get data and put in compute method for parse it.
networklayer.dart
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 parse response in a separate isolate return compute(parseData, response.body); }
once response received from the server, parse it with bellow method. It will create an instance of Country model and parse it.
networklayer.dart
List<Country> parseData(String responseBody) { final parsed = json.decode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<Country>((json) => new Country.fromJson(json)).toList(); }

3. Now, create a ListView widget that will show a group of items. Here, we use a card widget as a container of the list and two texts for display name and capital of the country
list.dart
@override Widget build(BuildContext context) { return new ListView.builder( itemCount: country == null ? 0 : country.length, itemBuilder: (BuildContext context, int index) { return new Card( child: new Container( child: new Center( child: new Column( // Stretch the cards in horizontal axis crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ new Text( // Read the name field value and set it in the Text widget country[index].name, // set some style to text style: new TextStyle( fontSize: 20.0, color: Colors.lightBlueAccent), ), new Text( // Read the name field value and set it in the Text widget "Capital:- " + country[index].capital, // set some style to text style: new TextStyle( fontSize: 20.0, color: Colors.amber), ), ], )), padding: const EdgeInsets.all(15.0), ), ); }); }

At the end merge code snippet and put in its files. Final project structure will look like this.



You can view and download all working files from below.
main.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_list_http_progress/country.dart'; import 'package:flutter_list_http_progress/list.dart'; import 'package:flutter_list_http_progress/netwoklayer.dart'; import 'package:http/http.dart' as http; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'World'; return new MaterialApp( title: appTitle, home: new MyHomePage(title: appTitle), ); } } class MyHomePage extends StatelessWidget { final String title; MyHomePage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(title), ), body: new FutureBuilder<List<Country>>( future: fetchCountry(new http.Client()), builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? new CountyList(country: snapshot.data) : new Center(child: new CircularProgressIndicator()); }, ), ); } }


networklayer.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter_list_http_progress/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 parse response 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>>(); return parsed.map<Country>((json) => new Country.fromJson(json)).toList(); }

list.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_list_http_progress/country.dart'; class CountyList extends StatelessWidget { final List<Country> country; CountyList({Key key, this.country}) : super(key: key); @override Widget build(BuildContext context) { return new ListView.builder( itemCount: country == null ? 0 : country.length, itemBuilder: (BuildContext context, int index) { return new Card( child: new Container( child: new Center( child: new Column( // Stretch the cards in horizontal axis crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ new Text( // Read the name field value and set it in the Text widget country[index].name, // set some style to text style: new TextStyle( fontSize: 20.0, color: Colors.lightBlueAccent), ), new Text( // Read the name field value and set it in the Text widget "Capital:- " + country[index].capital, // set some style to text style: new TextStyle( fontSize: 20.0, color: Colors.amber), ), ], )), padding: const EdgeInsets.all(15.0), ), ); }); } }

country.dart
class Country { final String name; final String flag; final String capital; Country({this.name, this.flag, this.capital}); factory Country.fromJson(Map<String, dynamic> json) { return new Country( name: json['name'] as String, flag: json['flag'] as String, capital: json['capital'] as String, ); } }

That's all about the ListView with HTTP in Flutter. If have any query, please feel free to clarify it with comment section below. 


Share:

Get it on Google Play

React Native - Start Development with Typescript

React Native is a popular framework for building mobile apps for both Android and iOS. It allows developers to write JavaScript code that ca...