I'm implementing a custom grid layout system in Flutter using Stack and Positioned widgets. While the grid itself works correctly for positioning items, I can't get it to properly communicate its height to parent widgets.
Current Implementation:
I have a StackedGridDashboard
widget that:
- Calculates unit sizes based on available width and number of columns
- Positions child widgets using absolute positioning
- Calculates its total height based on items positions and dimensions
Here's the implementation:
class StackedGridDashboard extends StatelessWidget {
final List<DashboardItem> items;
final int column;
final double padding;
final double spacing;
final double ratio;
double calculateTotalHeight(double availableWidth) {
final unitSize = _calculateUnitSize(availableWidth, column);
if (items.isEmpty) return 0;
final maxY = items.map((item) => item.position.y + item.position.height).reduce(math.max);
final totalSpacingHeight = (maxY - 1) * spacing;
final totalContentHeight = maxY * unitSize.height;
return totalContentHeight + totalSpacingHeight + (padding * 2);
}
@override
Widget build(BuildContext context) {
return IntrinsicHeight(
child: LayoutBuilder(
builder: (context, constraints) {
final totalHeight = calculateTotalHeight(constraints.maxWidth - (padding * 2));
final unitSize = _calculateUnitSize(constraints.maxWidth, column);
return Container(
padding: EdgeInsets.all(padding),
width: constraints.maxWidth,
height: totalHeight,
child: Stack(
children: [
for (final item in items)
Positioned(
left: item.position.x * (unitSize.width + spacing),
top: item.position.y * (unitSize.height + spacing),
width: item.position.width * unitSize.width + (item.position.width - 1) * spacing,
height: item.position.height * unitSize.height + (item.position.height - 1) * spacing,
child: item.child,
),
],
),
);
},
),
);
}
}
Usage :
Column(
mainAxisSize: MainAxisSize.min,
children: [
_DesktopHeader(),
kSmallGap,
SizedBox(
height: 1000, // Need this fixed height for it to work
width: double.infinity,
child: StackedGridDashboard(
column: 14,
items: [
DashboardItem(
position: GridPosition(x: 0, y: 0, width: 4, height: 3),
child: AncestorsCard.dynamic(manager: manager),
),
// More items...
],
),
),
],
)
Problem: Currently, I have to wrap the StackedGridDashboard in a SizedBox with a fixed height for it to display correctly. The calculateTotalHeight method returns the correct value, but this height doesn't propagate up to influence the parent layout.
What I've tried:
Using IntrinsicHeight Using LayoutBuilder Setting mainAxisSize: MainAxisSize.min on the Column Various combinations of Container constraints
The grid items position themselves correctly within the Stack, but I can't get the widget to size itself properly based on its content.
Question: How can I make my custom grid layout properly communicate its intrinsic height to parent widgets? Is there a specific way to handle height constraints with Stack and Positioned widgets?