castOrElse<T> function
Casts the given dynamic JSON value to the specified type T
.
Optionally, you can provide a transformer
function to transform the value manually if it is not null.
If the value is null, the orElse
function is called to return a default value.
Implementation
T? castOrElse<T>(
dynamic json, {
T? Function(Object value)? transformer,
T Function()? orElse,
}) {
try {
if (json == null) {
return orElse?.call();
}
if (transformer != null) {
return transformer(json);
}
if (json is! T) {
return orElse?.call();
}
return json;
} catch (_) {
return orElse?.call();
}
}