build method
Describes the part of the user interface represented by this widget.
The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.
The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.
Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.
The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.
The implementation of this method must only depend on:
- the fields of the widget, which themselves must not change over time, and
- any ambient state obtained from the
contextusing BuildContext.dependOnInheritedWidgetOfExactType.
If a widget's build method is to depend on anything else, use a StatefulWidget instead.
See also:
- StatelessWidget, which contains the discussion on performance considerations.
Implementation
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus();
},
behavior: HitTestBehavior.translucent,
child: LayoutBuilder(
builder: (context, constraints) {
// --- 1. Get Screen Constraints ---
double availableWidth = constraints.maxWidth;
if (!constraints.hasBoundedWidth) {
availableWidth = MediaQuery.of(context).size.width;
}
// --- 2. Determine Total Columns ---
int totalCols = 0;
if (headers.isNotEmpty) {
for (var cell in headers.first) {
totalCols += cell.colSpan;
}
} else if (tableData.isNotEmpty) {
totalCols = tableData.first.length;
}
// --- DATA SAMPLING ---
// For massive datasets, we CANNOT measure millions of rows.
// We sample the first 100 rows to establish base widths and heights.
final int sampleLimit = tableData.length > 100 ? 100 : tableData.length;
// --- 3. Calculate Base Content Widths ---
final double paddingOffset = 24.0; // Buffer for padding inside the cell
// Initialize with custom widths if provided, otherwise fallback to 80.0 minimum
List<double> resolvedWidths = List.generate(totalCols, (index) {
return indexWiseColumnWidths?[index] ?? 80.0;
});
// Measure Body Data (Sampled)
for (int r = 0; r < sampleLimit; r++) {
var row = tableData[r];
for (int c = 0; c < row.length && c < totalCols; c++) {
// SKIP heavy text measurement if this column has a fixed custom width
if (indexWiseColumnWidths != null && indexWiseColumnWidths!.containsKey(c)) {
continue;
}
double w = _measureTextSize(row[c].exportValue, textSize, isBold: row[c].exportIsBold).width + paddingOffset;
if (w > resolvedWidths[c]) resolvedWidths[c] = w;
}
}
final double verticalPadding = 16.0; // 8px top, 8px bottom buffer
// Measure Header Heights
List<double> resolvedHeaderHeights = List.filled(headers.length, headerRowHeight ?? 0.0);
if (headerRowHeight == null) {
for (int r = 0; r < headers.length; r++) {
double maxH = 40.0; // Minimum header height
int c = 0;
for (var cell in headers[r]) {
double spanWidth = 0;
for (int i = 0; i < cell.colSpan; i++) {
if (c + i < totalCols) spanWidth += resolvedWidths[c + i];
}
// Measure height given the constrained width
Size size = _measureTextSize(cell.text, headerTextSize, isBold: true, maxWidth: spanWidth - paddingOffset);
if (size.height + verticalPadding > maxH) maxH = size.height + verticalPadding;
c += cell.colSpan;
}
resolvedHeaderHeights[r] = maxH;
}
}
// Measure Body Heights (Sampled & Filled)
// Default all rows to 48.0 (or user provided), then strictly measure the sample.
List<double> resolvedBodyHeights = List.filled(tableData.length, bodyCellHeight ?? 48.0);
if (bodyCellHeight == null) {
for (int r = 0; r < sampleLimit; r++) {
double maxH = 48.0;
for (int c = 0; c < tableData[r].length && c < totalCols; c++) {
Size size = _measureTextSize(tableData[r][c].exportValue, textSize, isBold: tableData[r][c].exportIsBold, maxWidth: resolvedWidths[c] - paddingOffset);
if (size.height + verticalPadding > maxH) maxH = size.height + verticalPadding;
}
resolvedBodyHeights[r] = maxH;
}
}
// --- 4. THE RESPONSIVENESS FIX (Stretch to Fill Screen) ---
// If the calculated table width is smaller than the screen width, stretch the columns to fill the gap.
double totalNeededWidth = resolvedWidths.fold(0.0, (a, b) => a + b);
if (totalNeededWidth < availableWidth) {
double extraSpace = availableWidth - totalNeededWidth;
// Calculate total weight of ONLY the auto-sized columns
double autoColumnsWeight = 0;
for (int i = 0; i < resolvedWidths.length; i++) {
if (indexWiseColumnWidths == null || !indexWiseColumnWidths!.containsKey(i)) {
autoColumnsWeight += resolvedWidths[i];
}
}
if (autoColumnsWeight > 0) {
// Stretch only the columns that don't have explicit custom widths
for (int i = 0; i < resolvedWidths.length; i++) {
if (indexWiseColumnWidths == null || !indexWiseColumnWidths!.containsKey(i)) {
resolvedWidths[i] += extraSpace * (resolvedWidths[i] / autoColumnsWeight);
}
}
} else {
// Edge case: All columns are custom, but they still don't fill the screen.
// Fallback to standard stretching so it doesn't look broken.
for (int i = 0; i < resolvedWidths.length; i++) {
resolvedWidths[i] += extraSpace * (resolvedWidths[i] / totalNeededWidth);
}
}
}
// --- 5. Build the Grid Engine ---
return NrbTableEngineBuilder(
isSortingEnable: isSortingEnable,
columnWidths: resolvedWidths,
headerHeights: resolvedHeaderHeights,
bodyRowHeights: resolvedBodyHeights,
frozenColumnsCount: frozenColumnsCount,
headers: headers,
tableData: tableData,
primaryUiColor: primaryUiColor,
primaryUiTextColor: primaryUiTextColor,
enableDownload: enableDownload,
showDownloadFloatingButton: showDownloadFloatingButton,
packageName: packageName,
apiKey: apiKey,
reportName: reportName,
onDownloadCompleted: onDownloadCompleted,
controller: controller,
);
},
),
);
}