Article Image

Parsing JSON in Dart/Flutter

24th August 2020

Hi everybody!

There are many ways to parse JSON from requests. In this post, we are going to code how to parse JSON using http package in Flutter and Dart.

At first, we need to add http dependency in pubspec.yaml

http: ^0.12.2

We are going to make a request, it's taking a long time. That's why we need to use asynchronous programming. Otherwise, the user interface will be frozen waiting for a response from the request. We don't want that!

Dart provides two different ways to asynchronous programming: future and the async and await keywords. We are going to use both of them to code this example.

Note: in future posts, we can talk about asynchronous programming. In this post, we are going to focus on parsing JSON.

Let's code!

Imagine we need to get Flutter repositories from Github. So, we need to create a model which represents this repository.

Repository model

We can code using async and await keywords and it looks like this:

Parse response using async and await keyword

Let's analyze point by point:

1- get(url) is a function from http the package which response a Future<Response> but we used await keywords it returns just Response.

2- Response contains body which is a string. JSON could be parsed json from Dart package. import 'dart:convert'; to List<dynamic>.

3- We need to iterate each element from List and map to our Repository.

Use await keyword to get completed results of an asynchronous expression. Use async keyword before a function's body to mark it as asynchronous.

Note: await keyword only works within an async function.

Another implementation is using Future. In this way, we don't use await and async keywords.

Parse response using Future

Future represents the result of an asynchronous operation, and can have two states: uncompleted or completed.

This is same steps in previous implementation without async or await keywords.

The difference is only syntactic sugar. Don't worry but is not recommended to merge these ways.

The important point is you should use asynchronous programming when a task takes a long time, i.e:

  • Fetching data over a network.
  • Writing to a database.
  • Reading data from a file.

The full code is available on GitHub.

If you want, you can read my previous Flutter articles!.

That's all folks!

Enjoy!

More Than Code LLC

Address: 8 The Green STE B, Dover, DE 19901

Contact: mtc.morethancode@gmail.com

© Copyright 2022 All right reserved to More Than Code LLC