render method

  1. @override
void render(
  1. Buffer buffer,
  2. Rect area
)
override

Renders the widget onto the provided buffer within the specified area.

Implementation

@override
void render(Buffer buffer, Rect area) {
  if (area.width <= 0 || area.height <= 0) return;

  final hasHeaders = headers.isNotEmpty;
  final headerRowsCount = hasHeaders ? 2 : 0;
  final usableHeight = area.height - headerRowsCount;

  if (usableHeight <= 0) return;

  // 1. Render Headers
  if (hasHeaders) {
    final headerSb = StringBuffer();
    for (var i = 0; i < headers.length; i++) {
      final width = i < columnWidths.length ? columnWidths[i] : 10;
      final text = headers[i];
      final chars = text.characters;
      final padded = chars.length >= width
          ? chars.take(width).toString()
          : chars.toString() + (' ' * (width - chars.length));
      headerSb.write(padded);
      if (i < headers.length - 1) headerSb.write(' ');
    }
    final headerChars = headerSb.toString().characters;
    final headerStr = headerChars.length >= area.width
        ? headerChars.take(area.width).toString()
        : headerChars.toString() + (' ' * (area.width - headerChars.length));
    buffer.writeString(0, 0, headerStr, headerStyle);

    // Render Divider Line
    final dividerChar = '─';
    final divider = dividerChar * area.width;
    buffer.writeString(0, 1, divider, borderStyle);
  }

  // 2. Adjust Scroll
  adjustScroll(usableHeight);

  // 3. Render Visible Rows
  for (var r = 0; r < usableHeight; r++) {
    final rowIdx = scrollOffset + r;
    if (rowIdx >= itemCount) break;

    final rowData = itemBuilder(rowIdx);
    final isSelected = rowIdx == selectedRowIndex;
    final currentStyle = isSelected ? selectedRowStyle : rowStyle;

    final rowSb = StringBuffer();
    for (var c = 0; c < headers.length; c++) {
      final width = c < columnWidths.length ? columnWidths[c] : 10;
      final cellText = c < rowData.length ? rowData[c] : '';
      final chars = cellText.characters;
      final padded = chars.length >= width
          ? chars.take(width).toString()
          : chars.toString() + (' ' * (width - chars.length));
      rowSb.write(padded);
      if (c < headers.length - 1) rowSb.write(' ');
    }

    final rowChars = rowSb.toString().characters;
    final targetY = headerRowsCount + r;

    for (var x = 0; x < area.width; x++) {
      final char = x < rowChars.length ? rowChars.elementAt(x) : ' ';
      final cell = buffer.getCell(x, targetY);
      if (cell != null) {
        cell.char = char;
        cell.style = currentStyle;
      }
    }
  }
}