row method

List<int> row(
  1. List<PosColumn> cols
)

Print a row.

A row contains up to 12 columns. A column has a width between 1 and 12. Total width of columns in one row must be equal 12.

Implementation

List<int> row(List<PosColumn> cols) {
  List<int> bytes = [];
  final isSumValid = cols.fold(0, (int sum, col) => sum + col.width) == 12;
  if (!isSumValid) {
    throw Exception('Total columns width must be equal to 12');
  }
  bool isNextRow = false;
  List<PosColumn> nextRow = <PosColumn>[];

  for (int i = 0; i < cols.length; ++i) {
    int colInd =
        cols.sublist(0, i).fold(0, (int sum, col) => sum + col.width);
    double charWidth = _getCharWidth(cols[i].styles);
    double fromPos = _colIndToPosition(colInd);
    final double toPos =
        _colIndToPosition(colInd + cols[i].width) - spaceBetweenRows;
    int maxCharactersNb = ((toPos - fromPos) / charWidth).floor();

    Uint8List encodedToPrint = cols[i].textEncoded != null
        ? cols[i].textEncoded!
        : _encode(cols[i].text);

    // If the col's content is too long, split it to the next row
    int realCharactersNb = encodedToPrint.length;
    if (realCharactersNb > maxCharactersNb) {
      // Print max possible and split to the next row
      Uint8List encodedToPrintNextRow =
          encodedToPrint.sublist(maxCharactersNb);
      encodedToPrint = encodedToPrint.sublist(0, maxCharactersNb);
      isNextRow = true;
      nextRow.add(PosColumn(
          textEncoded: encodedToPrintNextRow,
          width: cols[i].width,
          styles: cols[i].styles));
    } else {
      // Insert an empty col
      nextRow.add(PosColumn(
          text: '', width: cols[i].width, styles: cols[i].styles));
    }
    // end rows splitting
    bytes += _text(
      encodedToPrint,
      styles: cols[i].styles,
      colInd: colInd,
      colWidth: cols[i].width,
    );
  }

  bytes += emptyLines(1);

  if (isNextRow) {
    row(nextRow);
  }
  return bytes;
}