callToJson static method
Calls o.toJson
in a performatic way, avoiding NoSuchMethodError and noSuchMethod calls.
- Returns
null
ifo
isnull
. - If
o
doesn't have atoJson
methodfallback
is called. Iffallback
is not provided it will callo.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 calltoJson
and will always perform afallback
.
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;
}
}