Parsing JSON in Dart/Flutter
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
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.
Imagine we need to get Flutter repositories from Github. So, we need to create a model which represents this repository.
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:
get(url) is a function from http the package which response a
Future<Response> but we used await keywords it returns just
2- Response contains body which is a string. JSON could be parsed json from Dart package.
import 'dart:convert'; to
3- We need to iterate each element from List and map to our
await keyword to get completed results of an asynchronous expression.
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
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
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!