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
What it reports
Section titled “What it reports”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, ofdecodeof aJsonCodecsuch asjson, ofconvertof aJsonDecoder, or of a function or method thatdecodersnames; - an index into decoded JSON, also through a
!or a cast toMap<String, dynamic>orList<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>orMap<String, Object?>, which holds; - a map from anywhere else, which may be built by hand with typed elements. Name in
decodersthe 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.
Example
Section titled “Example”factory Post.fromJson(Map<String, dynamic> json) => Post(tags: json['tags'] as List<String>);factory Post.fromJson(Map<String, dynamic> json) => Post(tags: List<String>.from(json['tags'] as List<dynamic>));Rule parameters
Section titled “Rule parameters”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. |
Suppressing it
Section titled “Suppressing it”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_collectionfinal 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.