valueAsBigInt<T extends BigInt?> static method

T valueAsBigInt<T extends BigInt?>(
  1. Object? value, {
  2. bool allowHex = false,
  3. bool? sign,
  4. bool allowDecimals = false,
})

Coerces value (int/String/hex/decimal string) to a BigInt.

Implementation

static T valueAsBigInt<T extends BigInt?>(
  Object? value, {
  bool allowHex = false,
  bool? sign,
  bool allowDecimals = false,
}) {
  final T v = (() {
    if (value is T) {
      return value;
    }
    if (value == null && _isNull<T>()) return null as T;
    final toBigint = BigintUtils.tryParse(value, allowHex: allowHex);
    if (toBigint == null) {
      if (allowDecimals && value is String) {
        final decode = BigRational.tryParse(value);
        if (decode != null) return decode.toBigInt() as T;
      } else if (value is double && value == value.truncateToDouble()) {
        final decode = BigRational.tryParse(value.toString());
        if (decode != null) return decode.toBigInt() as T;
      }
      throw CoreErrors.jsonWrongType("Failed to parse value as bigint.");
    }
    return toBigint as T;
  }());
  if (v == null) return v;
  if (sign != null && !sign && v.isNegative) {
    throw CoreErrors.jsonWrongType(
      "Invalid unsigned bigint.",
      details: {"value": v.toString()},
    );
  }
  return v;
}