Flutter Parsing JSON API in the background

We all know that , In Flutter Dart lang do all of their work on a single request. In most of the  cases, this model simplifies coding and is fast development that it does not result in poor app performance or stuttering animations, In this tutorial we are using Json API to fetch images and displaying them to the user.

To do this, we have to perform an expensive computation, such as parsing a very large JSON document. It will takes very less time achieve this in Flutter, After completion of  app your users will experience jank. In Flutter, we  can use a separate Isolate to avoid this jank.

Steps to follow for Parsing JSON  API in the background in flutter App:

  • Add the http package
  • Make a network request using the http package
  • Convert the response into a List of Photos
  • Move this work to a separate isolate

Add the dependency package to flutter app:

First, adding the http  dependency package to your project. The http package makes it easier to perform network requests over the internet, such as fetching data from a JSON API. Add the below code to spec.yaml file

dependencies:
http:

After adding the code in spec.yaml file. run get method to import all the files. without adding if we import it will shows error that is package not found error. 

Make a network request

In this example, we are going to fetch a JSON API that is Rest API  that contains large amount of data using  the JSONPlaceholder REST API using the http.get() method.

Future fetchPhotos(http.Client client) async {
return client.get('https://jsonplaceholder.typicode.com/photos');
}

Note:  In this example  we are providing an http.Client to the function. This  function  makes easier to test and use in different environments.

 Parse and Convert the json API into a List of Photos:

Now Fetch data from the internet  we have explained this in our earlier tutorial, we have to convert the http.Response into a list of Dart objects. This makes the data easier to work with in the future.

Create a Photo class :

Now , create a Photo class that contains details about a photo.We have to include a fromJson factory method to make it easy to create a Photo starting with a json object.

class Photo {
final int id;
final String title;
final String thumbnailUrl;

Photo({this.id, this.title, this.thumbnailUrl});

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

Convert the response into a List of Photos In flutter App:

The  fetchPhotos function  return a Future.  For this we have to perform following two things:

  • Create a parsePhotos that converts the response body into a List
  • Use the parsePhotos function in the fetchPhotos function

// A function that converts a response body into a List
List parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast>();

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

Future> fetchPhotos(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/photos');

return parsePhotos(response.body);
}

Move above code to a separate isolate:

The fetchPhotos function runs on a slower phone, we notice that the app freezes for a little bit a moment as it parses and converts the json. This is jank, and we want to aware of it.

We can solve this issue by moving the parsing and conversion to a background isolate using the computefunction provided by Flutter.  In background The compute function runs expensive functions and  isolate and returns the result. In this case, we want to run the parsePhotos function in the background.

Future> fetchPhotos(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/photos');

// Use the compute function to run parsePhotos in a separate isolate
return compute(parsePhotos, response.body);
}

Complete example code for  Parsing JSON API  in Flutter:

import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future> fetchPhotos(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/photos');

// Use the compute function to run parsePhotos in a separate isolate
return compute(parsePhotos, response.body);
}

// A function that converts a response body into a List
List parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast>();

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

class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;

Photo({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

factory Photo.fromJson(Map json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Isolate Demo';

return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}

class MyHomePage extends StatelessWidget {
final String title;

MyHomePage({Key key, this.title}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);

return snapshot.hasData
? PhotosList(photos: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}

class PhotosList extends StatelessWidget {
final List photos;

PhotosList({Key key, this.photos}) : super(key: key);

@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return Image.network(photos[index].thumbnailUrl);
},
);
}
}

Congratulations You Have Learned  Parsing JSON API in Flutter….!!!

If It Is Helpful Share It With Your Friends….!!!

Leave a Reply

Categories