valueTo<T extends Object?, VV extends Object?> method

T valueTo<T extends Object?, VV extends Object?>({
  1. required K key,
  2. required T parse(
    1. VV v
    ),
  3. bool? allowHex,
  4. StringEncoding? encoding,
  5. bool asBytes = false,
  6. T onMissing()?,
  7. T onError(
    1. BuError err
    )?,
  8. 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);
  }
}