You write a model, the first API response parses fine, and a week later a crash report says:
type 'int' is not a subtype of type 'double' in type cast
Enter fullscreen mode
Exit fullscreen mode
Nothing in your code changed. The data did. Here are the three type errors I see most often with jsonDecode , why they happen, and how to write (or generate) models that survive real responses.
1. int vs double
Dart's jsonDecode reads the number type from the text. 1.0 is a double , 1 is an int :
import 'dart:convert' ;
void main () { final a = jsonDecode ( '{"price": 1.0}' ) as Map < String , dynamic >; print ( a [ 'price' ] . runtimeType ); // double
final b = jsonDecode ( '{"price": 1}' ) as Map < String , dynamic >; final price = b [ 'price' ] as double ; // type 'int' is not a subtype of type 'double' in type cast }
Enter fullscreen mode
Exit fullscreen mode
Many backends drop the .0 for whole numbers, so a price of 3.0 arrives as 3 .…