Menu

1 / 2

Why your Flutter JSON model crashes at runtime (and how to generate one that doesn't)

DEV Community: dart·Chanpenh Yorn·20 days ago
#IVE9Ffyc
#devtodart#devto#dev#json#price
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.