adjustTableHeaderWidths method

void adjustTableHeaderWidths()

Implementation

void adjustTableHeaderWidths() {
  const double totalTableWidth = 580;
  final visible = tableVisibleHeaders
      .map(
        (element) => element['name'] as String,
  )
      .toList();

  // Calculate total width needed for all visible columns
  double totalUsedWidth = visible.fold(
      0,
          (sum, h) =>
      sum +
          (tableVisibleHeaders
              .firstWhereOrNull((value) => value['name'] == h)?['width']));

  if (totalUsedWidth > totalTableWidth) {
    // Calculate reduction ratio for all columns
    double reductionRatio = totalTableWidth / totalUsedWidth;

    // Apply reduction to all columns
    visible.forEach((header) {
      double currentWidth = tableVisibleHeaders.firstWhereOrNull(
              (value) => value['name'] == header)?['width'] ??
          70;
      double newWidth = currentWidth * reductionRatio;

      // Ensure minimum width of 10 pixels
      if (newWidth < 10) newWidth = 10;

      tableVisibleHeaders.firstWhereOrNull(
              (value) => value['name'] == header)?['width'] = newWidth;
    });

    // Verify total width after adjustment
    double newTotalWidth = visible.fold(
        0,
            (sum, h) =>
        sum +
            (tableVisibleHeaders.firstWhereOrNull(
                    (value) => value['name'] == h)?['width'] ??
                70));

    // If still over limit, reduce further
    if (newTotalWidth > totalTableWidth) {
      double finalReductionRatio = totalTableWidth / newTotalWidth;
      visible.forEach((header) {
        double currentWidth = tableVisibleHeaders.firstWhereOrNull(
                (value) => value['name'] == header)?['width'] ??
            70;
        double newWidth = currentWidth * finalReductionRatio;
        if (newWidth < 10) newWidth = 10;
        tableVisibleHeaders.firstWhereOrNull(
                (value) => value['name'] == header)?['width'] = newWidth;
      });
    }
  }
}