Flutter HTTP Client example with ListView – Fetch data and parse JSON in background

In this tutorial, we’re gonna build a Flutter App that use http package to fetch data from the internet, then parse JSON to a Dart List of Objects and display that List in ListView widget.

Related Post: Flutter ListView example with ListView.builder

Flutter App Overview

We will build a Flutter App that can display a List of Post objects gotten from JSONPlaceholder REST API. We are parsing JSON document that performs an expensive computation in the background.

flutter-http-example-listview-fetch-data-json-background

HTTP Fetch Data in background and Display in ListView

Add http package

Add this package to the dependencies section of our pubspec.yaml:

Create DataModel class

Parse JSON into a List of Objects

We will convert our HTTP Response into a list of Dart objects.

Fetch Data in a separate isolate

This is how we fetch data using the get method:

If we run the fetchPosts() function on a slower phone, the App may freeze for a moment when it parses and converts the JSON.

>> So we are moving the parsing and conversion to a background isolate using Flutter compute() function. This function runs parsePosts() in a background isolate and return the result.

Display the data

In order to display fetched data on screen, we can use the FutureBuilder widget with two parameters:
– The Future to work with. In our case, the return of fetchPosts() function.
– A builder function that tells Flutter what to render, depending on the state of the Future: loading, success, or error.

ListView widget uses ListView.builder:

Practice

Add http package

Add this package to the dependencies section of our pubspec.yaml:

Create DataModel Class

lib/post.dart

Create Main App Widget

lib/main.dart

Create Widget for fetching and parsing data

lib/home.dart

Create ListView Widget

lib/listpost.dart

Source Code

http_example

By grokonez | July 8, 2018.



Related Posts


2 thoughts on “Flutter HTTP Client example with ListView – Fetch data and parse JSON in background”

  1. thanks for this article, helped me get started with my project.
    One think that I ran into and could not figure out was how to add http client timeout and show message for it.
    Is that something you have an example of ?

    1. Hi Peder,

      We have 2 ways to set Timeout for HTTP Request:
      – use Future.timeout() method:

      – use HttpClient.connectionTimeout() method => apply to all requests made by the same client. When a request exceeds this timeout, a SocketException is thrown:

      Regards,
      grokonez.

Got Something To Say:

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

*