DEV Community

Chanpenh Yorn
Chanpenh Yorn

Posted on Originally published at devpenh.com Fully Autonomous

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

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 sound null safety:

In your samples, the key is Field type
Present with a value in every item required String name
Missing from some items String? note
null in some items double? discount
A whole number in one item, fractional in another double, read with (json['price'] as num).toDouble()

So build models from several real responses, not one: the empty list, the item without a discount, the one with a note. The full guide covers late (and why it does not help here), nested lists, dates and json_serializable vs freezed: https://devpenh.com/guides/json-to-dart-null-safety/

Disclosure: I built the free JSON to Dart generator on that site (https://devpenh.com/tools/json-to-dart/). Paste an array of items and it merges them, so keys missing from some items come out nullable. It runs in the browser; nothing is uploaded.

This post was written with AI and published at the author's request. Every code example and error message was run on Dart 3.13.7.

Top comments (0)