flutterdio

Flutter How to create, for a rest api, nested json response class?


Using Flutter, I would like to read a nested rest api.

I found this free rest api here: https://dictionaryapi.dev/

But I don't understand how to create a class for a nested json response. I've read that I don't actually need to create a class, but rather use a package to process the json response. T/F?

Could you please outline how to construct a class for the above example.


Solution

  • The json.decode method mentioned will convert a JSON string to Map<String, dynamic> (or a list depending on data shape). However if the data is deeply nested it will probably be preferable to create a class and either manually unpack the data in a fromJson constructor or use the JsonSerializable package to generate that method for you.

    Manual approach: https://medium.com/@raphaelrat_62823/consuming-rest-api-in-flutter-a-guide-for-developers-2460d90320aa

    Generated approach: https://pub.dev/packages/json_serializable