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
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:
name: json.containsKey("name") ? json["name"] ?? "" : "",
Now, if you wish to parse your API Response, simply call our function as:
Welcome _data = welcomeFromJson(response.body);
To access data:
Don’t stop, until you are breathing!💙
- Abhishek Doshi