Parsing JSON in Flutter!

Working with APIs? The response usually comes in JSON format!

Image copyright to the respective owner

So, whenever you work with API, we usually get responses in JSON format. JSON format looks somewhat like the below:

Now one way to parse JSON is to manually parse. However, when you are working with long responses, it becomes difficult.

It’s better to use model classes for the same. So we have a website where we just need to provide our entire JSON. You can check it out at: https://app.quicktype.io and select language as Dart

For the above JSON, we will get the following model class:

So you can see it becomes so simple to use quicktype to generate model classes. However, we should always add one more thing i.e. json.containsKey and whether the data is null or not. So after adding that, we will have the following model class:

This will make your app work even if the response missed some key or if any value is null.

So, it’s preferable to use QuickType as it makes your development faster.

Note: You can of course use Null Safety for checking null conditions. Eg:

Now, if you wish to parse your API Response, simply call our function as:

To access data:

Hope you enjoyed this article!

If you loved it, you can Buy Me A Coffee!

Don’t forget to connect with me on:

Don’t stop, until you are breathing!💙
- Abhishek Doshi

Flutter Developer