prefer-correct-json-casts
preset: recommended
Warns when a JSON object type cast is done in an unsafe way that will throw at runtime.
Casting a JSON object to a Map or List with generic types specified as anything except Object? / Object / dynamic can lead to a runtime exception. Instead, cast first to Object?
and then to the desired type.
Example
❌ Bad:
void main() {
final jsonRaw = '{"items": {"hello": 1}}';
final items = json['items'] as Map<String, int>; // LINT: Using 'Map' as generic type will throw at runtime. Replace with 'Object?' and cast separately.
final jsonRaw = '{"items": [1, 2, 3]}';
final items = json['items'] as List<int>; // LINT: Using 'List' as generic type will throw at runtime. Replace with 'Object?' and cast separately.
if (json case Object() as List<String>) {} // LINT: Using 'List' as generic type will throw at runtime. Replace with 'Object?' and cast separately.
}
✅ Good:
import 'dart:convert';
void main() {
final jsonRaw = '{"items": {"hello": 1}}';
final json = jsonDecode(jsonRaw) as Map<String, Object?>;
final items = (json['items'] as Map<String, Object?>).cast<String, int>();
final jsonRaw = '{"items": [1, 2, 3]}';
final json = jsonDecode(jsonRaw) as Map<String, Object?>;
final items = (json['items'] as List<Object?>).cast<int>().toList();
}