Skip to content

json_cast_to_typed_collection

Reports a cast of decoded JSON to a collection of a narrower element type, which throws on real JSON. Cast to List<dynamic> or Map<String, dynamic> and convert the elements.

Tier
blocking
Scope
Dart
Lowest preset
recommended
Fix
none

A cast of decoded JSON to a list, an iterable or a map of a narrower element type than decoding gives: jsonDecode(text) as List<String>, json['tags'] as List<String>, data as Map<String, String>. The violation is on the cast.

Decoding makes every list a List<dynamic> and every map a Map<String, dynamic>, whatever they hold. So such a cast throws wherever the value is a collection.

A value is decoded JSON where the rule can see it:

  • the result of jsonDecode, of decode of a JsonCodec such as json, of convert of a JsonDecoder, or of a function or method that decoders names;
  • an index into decoded JSON, also through a ! or a cast to Map<String, dynamic> or List<dynamic>;
  • a local variable initialized with one of these and never assigned again;
  • a parameter of a constructor, method or function named fromJson.

It does not report:

  • a cast to List<dynamic>, List<Object?>, Map<String, dynamic> or Map<String, Object?>, which holds;
  • a map from anywhere else, which may be built by hand with typed elements. Name in decoders the call of a package’s client that gives decoded JSON, such as a response body it already decoded.

The cast reads like a conversion and compiles. A test that passes a typed list literal to fromJson passes as well. Only real JSON makes it throw, on the first list. AI coding agents write this often in a hand-written fromJson.

Violating
factory Post.fromJson(Map<String, dynamic> json) =>
Post(tags: json['tags'] as List<String>);
Corrected
factory Post.fromJson(Map<String, dynamic> json) =>
Post(tags: List<String>.from(json['tags'] as List<dynamic>));

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
decoders [] More functions and methods whose result is decoded JSON, by name, such as your own wrapper of jsonDecode.
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression, which goes above the line of the cast:

// The tests replace the decoder with one that types its lists.
// ignore: json_cast_to_typed_collection
final tags = jsonDecode(text) as List<String>;

// ignore_for_file: assay/json_cast_to_typed_collection silences it in a whole file, and // ignore: assay/json_cast_to_typed_collection with the prefix works too. See Suppressions.