jsonDecodeSafe static method

  1. @useResult
dynamic jsonDecodeSafe(
  1. String? jsonString
)

Safely decodes a JSON string, returning null on error. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
static dynamic jsonDecodeSafe(String? jsonString) {
  final String? trimmed = jsonString?.trim();
  if (trimmed == null || trimmed.isEmpty || trimmed == 'null') return null;
  if (!isJson(trimmed)) return null;

  try {
    return dc.jsonDecode(trimmed);
  } on FormatException catch (e, stackTrace) {
    // Structured log instead of debugPrint, so the stack trace is not printed
    // to stdout; the caller still gets null as the failure signal.
    log('JsonUtils.jsonDecodeSafe failed', error: e, stackTrace: stackTrace);

    return null;
  }
}