asInt function

int? asInt(
  1. String text, {
  2. int? defaultValue,
})

Converts a text into an integer. defaultValue is the return value if text is not an integer

Implementation

int? asInt(String text, {int? defaultValue}) {
  var rc = defaultValue;
  if (text.isNotEmpty) {
    final match = _regExprInt.firstMatch(text);
    if (match != null) {
      var negate = text.startsWith('-');
      if (match.groupCount >= 3 && match.group(3) != null) {
        rc = int.parse(match.group(3) ?? '');
      } else if (match.groupCount >= 2 && match.group(2) != null) {
        rc = int.parse(match.group(2) ?? '', radix: 8);
      } else {
        rc = int.parse(text);
      }
      if (negate) {
        rc = -rc;
      }
    }
  }
  return rc;
}