pragmatic_flutter
pragmatic_flutter copied to clipboard
Models fail to parse when json fields don't exist (Chapter 13)
https://github.com/ptyagicodecamp/pragmatic_flutter/blob/affb371438f87044a1c797fba2fab71218636d5d/lib/chapter13/part2/bookmodel.dart#L1
Hey Priyanka! The Google Books api sometimes omits returning json fields if they don't exist in the db, for example the 'subtitle' field isn't always returned. Sadly, Flutter was not returning any exception, warning, or any other indication that the parsing was failing due to this, which caused a lot of debug time.
The easiest fix I could find was to make any optional fields, like 'subtitle', null-optional. Simply doing this change means that the non-existent values in json can be represented as nullable fields in the model:
class VolumeInfo {
final String title;
final String? subtitle;
final String? description;
final List<dynamic>? authors;
final String? publisher;
final String? publishedDate;
final ImageLinks? imageLinks;
Alternatively, a more advanced ways of parsing the json using annotations or other code generation libs is available, such as this: https://medium.com/codechai/validating-json-in-flutter-6f07ec9344f8
Just wanted to put this note in the repo in case other people run into this issue too.
Thanks!