valueTo<T extends Object?, VV extends Object?> method
T
valueTo<T extends Object?, VV extends Object?>({
- required K key,
- required T parse(
- VV v
- bool? allowHex,
- StringEncoding? encoding,
- bool asBytes = false,
- T onMissing()?,
- T onError(
- BuError err
- bool normalizeKeyLookup = false,
Reads key, coerces it to VV, then applies parse to build a T.
Implementation
T valueTo<T extends Object?, VV extends Object?>({
required K key,
required T Function(VV v) parse,
bool? allowHex,
StringEncoding? encoding,
bool asBytes = false,
T Function()? onMissing,
T Function(BuError err)? onError,
/// Only applicable when [K] is `String`.
bool normalizeKeyLookup = false,
}) {
try {
V? value = this[key];
if (value == null && normalizeKeyLookup && key is String) {
final normalizedKey = _normalizeKey(key);
for (final entry in entries) {
final key = entry.key;
if (key is String && _normalizeKey(key) == normalizedKey) {
value = entry.value;
break;
}
}
}
if (value == null) {
if (JsonParser._isNull<VV>()) return parse(null as VV);
if (JsonParser._isNull<T>()) return null as T;
if (onMissing != null) return onMissing();
if (!containsKey(key)) throw CoreErrors.jsonKeyNotFound(key);
throw BuError(DefaultErrorType.badJson, "Null value for key: '$key'.");
}
return JsonParser.valueTo(
value: value,
parse: parse,
allowHex: allowHex,
asBytes: asBytes,
encoding: encoding,
);
} on BuError catch (e) {
if (onError != null) return onError(e);
throw CoreErrors.jsonErrorWithKey(e, key);
}
}