tryFromJson static method

ErrorDetail? tryFromJson(
  1. Map<String, dynamic> json
)

Attempts to parse an ErrorDetail from a single entry in an ErrorResponseModel's details array.

Validates the structure of json using JsonSentinel.validate before parsing. Returns null if validation fails, making this safe to call on untrusted API data.

Implementation

static ErrorDetail? tryFromJson(Map<String, dynamic> json) {
  final Map<String, List<Type?>?> expectedTypes = <String, List<Type?>?>{
    "field": <Type?>[String],
    "message": <Type?>[String],
    "code": <Type?>[null, String],
  };

  final bool ok = JsonSentinel.validate(
    json: json,
    expectedTypes: expectedTypes,
    optional: const <String>{'code'},
    context: 'ErrorDetail',
    escalate: false,
  ).isValid;

  if (!ok) return null;

  return ErrorDetail(field: json["field"] as String, message: json["message"] as String, code: json["code"] as String?);
}