DEV Community

loizenai
loizenai

Posted on

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

https://grokonez.com/flutter/flutter-http-client-example-listview-fetch-data-parse-json-background

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:

dependencies:
  http: 

Create DataModel class


class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

  factory Post.fromJson(Map json) {
    return Post(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
}

Parse JSON into a List of Objects

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

List<Post> parsePosts(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Post>((json) => Post.fromJson(json)).toList();
}

Fetch Data in a separate isolate

This is how we fetch data using the get method:

Future<List<Post>> fetchPosts(http.Client client) async {
  final response = await client.get('https://jsonplaceholder.typicode.com/posts');

  // compute function to run parsePosts in a separate isolate
  return parsePosts(response.body);
}

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.

More at:

https://grokonez.com/flutter/flutter-http-client-example-listview-fetch-data-parse-json-background

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

Top comments (0)