generate method

  1. @override
String generate({
  1. int? state,
})
override

This method generates a valid CPF, which is returned as a String

The optional state argument refers to the location of the CPF to be generated. If state isn't passed, then a random state will be selected in order to generate a valid CPF.

Usage:

final cpf = CPFUtil();
// This will generate 100 valid CPF
for (int i = 0; i < 100; i++) {
  print(cpf.generate()); // -> '352.753.028-27'
}

You can check the state of a CPF by looking at the last number before the two verifiers digits.

All the information about the generation and the states number can be obtained here:

https://pt.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas

Implementation

@override
String generate({int? state}) {
  var cpf = List<int>.generate(
    9,
    (index) => index == 8 ? state ?? random.nextInt(9) : random.nextInt(9),
    growable: true,
  );

  cpf.insert(9, _calculateVerifyingDigit(cpf));
  cpf.insert(10, _calculateVerifyingDigit(cpf));

  return format(cpf
      .map<String>((elements) => elements.toString())
      .reduce((a, b) => a += b));
}