callToJson static method

Object? callToJson(
  1. dynamic o, {
  2. Object? fallback(
    1. dynamic o
    )?,
})

Calls o.toJson in a performatic way, avoiding NoSuchMethodError and noSuchMethod calls.

  • Returns null if o is null.
  • If o doesn't have a toJson method fallback is called. If fallback is not provided it will call o.toString().
  • The implementation tracks which Types have a toJson method or not and once a Type is marked wihtout it due to a NoSuchMethodError it will no longer attempt to call toJson and will always perform a fallback.

Implementation

static Object? callToJson(dynamic o,
    {Object? Function(dynamic o)? fallback}) {
  if (o == null) return null;

  var t = o.runtimeType;

  var hasNoSuchMethodError = _callToJsonNoSuchMethodError[t];

  if (hasNoSuchMethodError != null) {
    if (hasNoSuchMethodError) {
      if (fallback != null) {
        return fallback(o);
      } else {
        return o.toString();
      }
    } else {
      // ignore: avoid_dynamic_calls
      return o.toJson();
    }
  }

  try {
    // ignore: avoid_dynamic_calls
    var ret = o.toJson();
    _callToJsonNoSuchMethodError[t] = false;
    return ret;
  } on NoSuchMethodError {
    _callToJsonNoSuchMethodError[t] = true;
    if (fallback != null) {
      return fallback(o);
    } else {
      return o.toString();
    }
  } catch (_) {
    _callToJsonNoSuchMethodError[t] = false;
    rethrow;
  }
}