encodeContent method

  1. @override
List<bool> encodeContent(
  1. String contents, [
  2. Map<EncodeHintType, Object?>? hints
])
override

Encode the contents to bool array expression of one-dimensional barcode. Start code and end code should be included in result, and side margins should not be included.

@param contents barcode contents to encode @return a {@code List

Implementation

@override
List<bool> encodeContent(
  String contents, [
  Map<EncodeHintType, Object?>? hints,
]) {
  final length = contents.length;
  switch (length) {
    case 12:
      // No check digit present, calculate it and add it
      int check;
      try {
        check = UPCEANReader.getStandardUPCEANChecksum(contents);
      } on FormatsException catch (fe) {
        throw ArgumentError(fe);
      }
      contents += check.toString();
      break;
    case 13:
      try {
        if (!UPCEANReader.checkStandardUPCEANChecksum(contents)) {
          throw ArgumentError('Contents do not pass checksum');
        }
      } on FormatsException catch (_) {
        throw ArgumentError('Illegal contents');
      }
      break;
    default:
      throw ArgumentError(
        'Requested contents should be 12 or 13 '
        'digits long, but got $length',
      );
  }

  OneDimensionalCodeWriter.checkNumeric(contents);

  final firstDigit = int.parse(contents[0]);
  final parities = EAN13Reader.FIRST_DIGIT_ENCODINGS[firstDigit];
  final result = List.filled(_CODE_WIDTH, false);
  int pos = 0;

  pos += OneDimensionalCodeWriter.appendPattern(
    result,
    pos,
    UPCEANReader.START_END_PATTERN,
    true,
  );

  // See EAN13Reader for a description of how the first digit & left bars are encoded
  for (int i = 1; i <= 6; i++) {
    int digit = int.parse(contents[i]);
    if ((parities >> (6 - i) & 1) == 1) {
      digit += 10;
    }
    pos += OneDimensionalCodeWriter.appendPattern(
      result,
      pos,
      UPCEANReader.lAndGPatterns[digit],
      false,
    );
  }

  pos += OneDimensionalCodeWriter.appendPattern(
    result,
    pos,
    UPCEANReader.MIDDLE_PATTERN,
    false,
  );

  for (int i = 7; i <= 12; i++) {
    final digit = int.parse(contents[i]);
    pos += OneDimensionalCodeWriter.appendPattern(
      result,
      pos,
      UPCEANReader.L_PATTERNS[digit],
      true,
    );
  }
  OneDimensionalCodeWriter.appendPattern(
    result,
    pos,
    UPCEANReader.START_END_PATTERN,
    true,
  );

  return result;
}