Menu

Your Dart model is right for one JSON response and wrong for the next
📰

Your Dart model is right for one JSON response and wrong for the next

DEV Community: dart·Chanpenh Yorn·13 days ago
#5x5kPFJs
#devtodart#devto#dev#json#type
Reading 0:00
15s threshold

Generating a Dart model from one sample response is fast, and it is usually wrong in a few places. Here is a product item from an API:

{ "id" : 102 , "name" : "USB-C cable" , "price" : 5 , "discount" : 0.15 , "tags" : [], "note" : "Ships in 2 days" }

Enter fullscreen mode

Exit fullscreen mode

A model built from this item alone guesses:

price: json [ 'price' ] as int , // 5 looked like an int discount: ( json [ 'discount' ] as num ) . toDouble (), // never null in this item tags: json [ 'tags' ] as List < dynamic >, // [] says nothing about the items note: json [ 'note' ] as String , // missing from other items

Enter fullscreen mode

Exit fullscreen mode

The next item has "price": 24.5 and "discount": null , and decoding it fails:

type 'double' is not a subtype of type 'int' in type cast

Enter fullscreen mode

Exit fullscreen mode

Fix that and it fails on the next field:

type 'Null' is not a subtype of type 'num' in type cast

Enter fullscreen mode

Exit fullscreen mode

The rule of thumb under…

Continue reading — create a free account

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