toMaskedCardNumber method

String toMaskedCardNumber({
  1. String obscureText = "•",
  2. int targetLength = 16,
  3. int seperatedBy = 4,
  4. bool substringFromEnd = true,
})

Implementation

String toMaskedCardNumber({
  String obscureText = "•",
  int targetLength = 16,
  int seperatedBy = 4,
  bool substringFromEnd = true,
}) {
  String targetVal = replaceAll(" ", "");
  if (targetVal.length < targetLength) {
    targetVal =
        List.generate(targetLength - targetVal.length, (index) => obscureText)
                .join() +
            targetVal;
  } else if (targetVal.length > targetLength) {
    if (substringFromEnd) {
      targetVal = targetVal.substring(targetVal.length - targetLength);
    } else {
      targetVal = targetVal.substring(0, targetLength);
    }
  }
  String result = "";
  if (seperatedBy > 0) {
    for (int i = 0; i < targetVal.length; i++) {
      result +=
          (i > 0 && i % seperatedBy == 0) ? " ${targetVal[i]}" : targetVal[i];
    }
  } else {
    result = targetVal;
  }
  return result;
}