Book model part 2
Data Layer
Summary
This lesson focuses on refining the auto-generated BookModel and its nested classes to prevent runtime crashes caused by JSON type mismatches. The primary issue addressed is the strict parsing of numbers, where an API might return a double for a field expected to be an int (or vice versa). To resolve this, the instructor demonstrates converting int or double fields to Dart's generic num type, ensuring safe and flexible JSON parsing within the Data Layer.
Key Ideas
- Auto-generated model extensions correctly handle basic null safety by defaulting missing internet data to null.
- Strict parsing of numeric types (as int or as double) from JSON can cause subtype errors if the API payload types fluctuate.
- Dart's num type is the parent class for both int and double, making it ideal for flexible numeric JSON parsing.
- Model properties that represent variables like ratings (e.g., averageRating, ratingsCount) should be changed from int? or double? to num?.
- The corresponding factory constructors (fromJson) must also be updated to cast the JSON value using as num? instead of as int?.
- Developers should manually verify all nested objects (like VolumeInfo or SaleInfo) to catch and update any lingering strict int casts.
Code Snippets
factory VolumeInfo.fromJson(Map<String, dynamic> json) => VolumeInfo(
// ... other fields ...
pageCount: json['pageCount'] as int?,
printType: json['printType'] as String?,
categories: (json['categories'] as List<dynamic>?)
?.map((e) => e as String)
.toList(),
averageRating: json['averageRating'] as num?,
ratingsCount: json['ratingsCount'] as num?,
// ...
);My Notes
The instructor highlights a very common pitfall in Flutter when consuming JSON APIs: Dart's strict type system throwing type 'double' is not a subtype of type 'int' when an API decides to send 10.0 instead of 10. Using num is a pragmatic and quick fix in the Data Layer model. [Editor's note] While using num in the DTO/Model prevents immediate crashes, your Domain Layer Entity should ideally remain strictly typed (e.g., using int for page counts). You can handle the explicit conversion from num to int (using .toInt()) in your Repository mapping layer. This keeps the Data Layer flexible but the Domain Layer mathematically strict, adhering perfectly to Clean Architecture principles.