Flutter Tutorial Part 4: Http Fetch data and parse JSON with ListView

Ying Chen
2 min readApr 22, 2019

In this tutorial, I will show you how to use Flutter HTTP Get a list of data and parse into JSON, then display in a list view. Also, with image cached.

YouTube Video uploaded. Speed x1.25 is better :)

First, add dependency packages:

http: ^0.12.0+2 and cached_network_image: ^0.7.0 to your pubspec.yaml file.

  1. https://pub.dartlang.org/packages/http , A composable, Future-based library for making HTTP requests.
  2. https://pub.dartlang.org/packages/cached_network_image A flutter library to show images from the internet and keep them in the cache directory.

Parse JSON DATA

I found a very good JSON example from https://unsplash.com

The link is https://unsplash.com/napi/photos/Q14J2k8VE3U/related

Using Http package get the data

Build ListView

Build a ListView Widget, the itemCount is data.length

Widget _buildListView() {
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemCount: data == null ? 0 : data.length,
itemBuilder: (context, index) {
return _buildImageColumn(data[index]);
}
);
}

Then Create a new widget to display the image:Widget _buildImageColumn(dynamic item)

Using CachedNetworkImage widget to display image.

new CachedNetworkImage(
imageUrl: item['urls']['small'],
placeholder: (context, url) => new CircularProgressIndicator(),
errorWidget: (context, url, error) => new Icon(Icons.error),
fadeOutDuration: new Duration(seconds: 1),
fadeInDuration: new Duration(seconds: 3),
),

Then build text

Widget _buildRow(dynamic item) {
return ListTile(
title: Text(
item['description'] == null ? '': item['description'],
),
subtitle: Text("Likes: " + item['likes'].toString()),
);
}

Your function should look like the following:

Widget _buildImageColumn(dynamic item) => Container(
decoration: BoxDecoration(
color: Colors.white54
),
margin: const EdgeInsets.all(4),
child: Column(
children: [
new CachedNetworkImage(
imageUrl: item['urls']['small'],
placeholder: (context, url) => new CircularProgressIndicator(),
errorWidget: (context, url, error) => new Icon(Icons.error),
fadeOutDuration: new Duration(seconds: 1),
fadeInDuration: new Duration(seconds: 3),
),
_buildRow(item)
],
),
);
Widget _buildRow(dynamic item) {
return ListTile(
title: Text(
item['description'] == null ? '': item['description'],
),
subtitle: Text("Likes: " + item['likes'].toString()),
);
}

Finally, call the Get JSON when app init.

@override
void initState() {
super.initState();
// Call the getJSONData() method when the app initializes
this.getJSONData();
}

Your finally main.dart should look like this

Thanks for reading.

Check out the git repo here.

--

--