isValidCNPJ static method

bool isValidCNPJ(
  1. String cnpj
)

Implementation

static bool isValidCNPJ(String cnpj) {
  // Remove caracteres especiais
  cnpj = cnpj.replaceAll(RegExp(r'[^0-9]'), '');

  // Verifica se o CNPJ tem 14 dígitos e não é uma sequência de números iguais
  if (cnpj.length != 14 || RegExp(r'^(\d)\1*$').hasMatch(cnpj)) {
    return false;
  }

  // Calcula o primeiro dígito verificador
  List<int> weights1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
  int sum = 0;
  for (int i = 0; i < 12; i++) {
    sum += int.parse(cnpj[i]) * weights1[i];
  }
  int firstCheckDigit = sum % 11;
  if (firstCheckDigit < 2) {
    firstCheckDigit = 0;
  } else {
    firstCheckDigit = 11 - firstCheckDigit;
  }

  if (firstCheckDigit != int.parse(cnpj[12])) {
    return false;
  }

  // Calcula o segundo dígito verificador
  List<int> weights2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
  sum = 0;
  for (int i = 0; i < 13; i++) {
    sum += int.parse(cnpj[i]) * weights2[i];
  }
  int secondCheckDigit = sum % 11;
  if (secondCheckDigit < 2) {
    secondCheckDigit = 0;
  } else {
    secondCheckDigit = 11 - secondCheckDigit;
  }

  if (secondCheckDigit != int.parse(cnpj[13])) {
    return false;
  }

  return true;
}