layout method

  1. @override
PwBox layout(
  1. Context context,
  2. BoxConstraints constraints
)
override

layout API.

Implementation

@override
PwBox layout(Context context, BoxConstraints constraints) {
  if (children.isEmpty) {
    return EmptyBox();
  }
  var cols = 1;
  for (final TableRow row in children) {
    if (row.children.length > cols) {
      cols = row.children.length;
    }
  }
  final double maxW = constraints.hasBoundedWidth ? constraints.maxWidth : 400;
  final List<double> widths = _resolveWidths(context, cols, maxW, constraints);
  final List<List<PwBox>> cells = <List<PwBox>>[];
  final List<double> rowH = <double>[];
  final List<TableCellVerticalAlignment> aligns =
      <TableCellVerticalAlignment>[];

  // Pass 1: measure with tight column width (height unconstrained).
  for (final TableRow row in children) {
    final TableCellVerticalAlignment align =
        row.verticalAlignment ?? defaultVerticalAlignment;
    aligns.add(align);
    final List<PwBox> measured = <PwBox>[];
    var h = 0.0;
    for (int c = 0; c < cols; c++) {
      final Widget child = c < row.children.length
          ? row.children[c]
          : const SizedBox.shrink();
      final PwBox box = child.layout(
        context,
        BoxConstraints.tightFor(width: widths[c]),
      );
      measured.add(box);
      if (box.size.height > h) {
        h = box.size.height;
      }
    }
    rowH.add(h < 14 ? 14 : h);
    cells.add(measured);
  }

  // Pass 2: re-layout to full cell size when alignment is [full]
  // (package:pdf default for fromTextArray — fills cell backgrounds).
  for (int r = 0; r < children.length; r++) {
    if (aligns[r] != TableCellVerticalAlignment.full) {
      continue;
    }
    final TableRow row = children[r];
    final List<PwBox> laid = <PwBox>[];
    for (int c = 0; c < cols; c++) {
      final Widget child = c < row.children.length
          ? row.children[c]
          : const SizedBox.shrink();
      laid.add(
        child.layout(
          context,
          BoxConstraints.tight(PwSize(widths[c], rowH[r])),
        ),
      );
    }
    cells[r] = laid;
  }

  var totalH = 0.0;
  for (final double h in rowH) {
    totalH += h;
  }
  final bool rtl = context.textDirection == TextDirection.rtl;
  final List<double> placedWidths = rtl
      ? widths.reversed.toList(growable: false)
      : widths;
  final List<List<PwBox>> placedCells = rtl
      ? <List<PwBox>>[
          for (final List<PwBox> row in cells) row.reversed.toList(),
        ]
      : cells;
  return _TableBox(
    constraints.constrain(PwSize(maxW, totalH)),
    placedWidths,
    rowH,
    placedCells,
    aligns,
    children,
    border,
    tableBorder,
    borderColor,
  );
}