decodeTypedNullable<T> function

T? decodeTypedNullable<T>(
  1. dynamic raw
)

Implementation

T? decodeTypedNullable<T>(dynamic raw) {
  final type = TypeCheck<T>();

  if (raw == null || type.isSubtypeOf<Null>()) {
    return null;
  }

  if (raw is T) {
    return raw;
  }

  if (type.isSubtypeOf<String?>()) {
    return raw.toString() as T;
  }

  if (type.isSubtypeOf<int?>()) {
    final result = int.tryParse(raw.toString());
    return (result is T) ? result as T : null;
  }

  if (type.isSubtypeOf<double?>()) {
    final result = double.tryParse(raw.toString());
    return (result is T) ? result as T : null;
  }

  if (type.isSubtypeOf<bool?>()) {
    if (raw is num) {
      return raw > 0 as T;
    }

    if (raw.toString().toLowerCase() == 'true') {
      return true as T;
    } else if (raw.toString().toLowerCase() == 'false') {
      return false as T;
    }

    return null;
  }

  if (type.isSubtypeOf<DateTime?>()) {
    final result = DateTime.tryParse(raw.toString());
    return (result is T) ? result as T : null;
  }

  if (type.isSubtypeOf<Uint8List?>()) {
    final str = raw.toString();
    if (str.isEmpty) {
      return null;
    }

    return Base64Decoder().convert(str) as T;
  }

  throw ApiError.invalidType(T);
}