How To Parse JSON in Flutter

From desktop apps to mobile apps, the utilization of JSON is just unavoidable. That is why it’s critical for us Flutter developers to learn such object notation, utilize it, and then mold it into whatever data we would like. That is why today we’ll learn how to parse JSON in Flutter! Let’s get started!

Despite Dart apps, by default, perform all of their work on a single thread. In many circumstances, this model simplifies development and is fast enough to avoid bad app performance or stuttering animations, sometimes known as “jank.”

You may, however, be required to do a costly computation, such as parsing a very large JSON document. Jank occurs when this work takes more than 16 milliseconds.

To avoid jank, expensive computations like this must be performed in the background. This involves scheduling tasks on a different thread in Android. You can utilize a distinct Isolate in Flutter.


Prerequisites For Parsing JSON In Flutter

Of course, we need to add the http package dependencies before we can start. We cannot accomplish our objective here today without them.

dependencies:
  http: <latest_version>

Parsing JSON In Flutter

To this end, the focal point of how to parse JSON in Flutter will be demonstrated using the code below. The code below parses our JSON into an object we could utilize, which is a Photo class, which we then utilize into a list for later use.

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

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

  factory Photo.fromJson(Map<String, dynamic> 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,
    );
  }
}
// Turning it into a list
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

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

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

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

App Freezing Prevention

If you use the fetchPhotos() function on a slower device, you may notice that the app briefly stalls as it parses and converts the JSON. This is garbage, and you want it gone.

You may eliminate the jank by transferring the parsing and converting to a background isolate and using Flutter’s compute() API. The compute() function executes expensive functions in the background and returns the output. Run the parsePhotos()function in the background in this situation.

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

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

Be warned that Isolates communicate by sending and receiving messages. These messages can be null, num, bool, double, or String values, or simple objects like the <ListPhoto> in our example. If you try to pass more complicated items across isolates, such as a Future or a http.Response, you may get issues.


Conclusion

To conclude, we learned how to parse JSON in Flutter. The code below parses our JSON into an object we could utilize, which is a Photo class, which we then utilize into a list for later use. We became aware that Isolates communicate by sending and receiving messages. These messages can be null, num, bool, double, or string values. There’s a ton of such application utilization in my past blogs, which you can visit here. If you find this information somewhat outdated in the future, you can always check the official documentation. Thank you, and once again, if you found this useful, please share it.

Leave a Comment

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