prefer-correct-json-casts
added in: 1.8.0
warning
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
final jsonRaw = '{"items": [1, 2, 3]}';
final items = json['items'] as List<int>; // LINT
if (json case Object() as List<String>) {} // LINT
}
✅ 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();
}