prefer-correct-json-casts
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}}';
// LINT: Using 'Map' as a generic type will throw at runtime.
// Replace it with 'Object?' and cast separately.
final items = json['items'] as Map<String, int>;
final jsonRaw = '{"items": [1, 2, 3]}';
// LINT: Using 'List' as a generic type will throw at runtime.
// Replace it with 'Object?' and cast separately.
final items = json['items'] as List<int>;
// LINT: Using 'List' as a generic type will throw at runtime.
// Replace it with 'Object?' and cast separately.
if (json case Object() as List<String>) {}
}
✅ 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();
}