getResponsiveGridListItems method
Method to generate a list of ResponsiveGridRow's with spacing in between them.
maxWidth
is the maximum width of the current layout.
Implementation
List<Widget> getResponsiveGridListItems(double maxWidth) {
// Start with the minimum allowed number of items per row.
var itemsPerRow = minItemsPerRow;
// Calculate the current width according to the items per row
var currentWidth =
itemsPerRow * minItemWidth + (itemsPerRow - 1) * horizontalGridSpacing;
// Add outer margin (vertical) if set
if (horizontalGridMargin != null) {
currentWidth += 2 * horizontalGridMargin!;
}
// While another pair of spacing + minItemWidth fits the row, add it to
// the variables. Only add items while maxItemsPerRow is not reached.
while (currentWidth < maxWidth &&
(maxItemsPerRow == null || itemsPerRow < maxItemsPerRow!)) {
if (currentWidth + (minItemWidth + horizontalGridSpacing) <= maxWidth) {
// If another spacing + item fits in the row, add one item to the row
// and update the currentWidth
currentWidth += minItemWidth + horizontalGridSpacing;
itemsPerRow++;
} else {
// If no other item + spacer fits into the row, break
break;
}
}
// Calculate the spacers per row (they are only in between the items, not
// at the edges)
final spacePerRow = itemsPerRow - 1;
// Calculate the itemWidth that results from the maxWidth and number of
// spacers and outer margin (horizontal)
final itemWidth = (maxWidth -
(spacePerRow * horizontalGridSpacing) -
(2 * (horizontalGridMargin ?? 0))) /
itemsPerRow;
// Partition the items into groups of itemsPerRow length and map them
// to ResponsiveGridRow's
final items = partition(children, itemsPerRow)
.map<Widget>(
(e) => ResponsiveGridRow(
rowItems: e,
spacing: horizontalGridSpacing,
horizontalGridMargin: horizontalGridMargin,
itemWidth: itemWidth,
),
)
.toList();
// Join the rows width spacing in between them (vertical)
final responsiveGridListItems =
items.genericJoin(SizedBox(height: verticalGridSpacing));
// Add outer margin (vertical) if set
if (verticalGridMargin != null) {
return [
SizedBox(height: verticalGridMargin),
...responsiveGridListItems,
SizedBox(height: verticalGridMargin),
];
}
return responsiveGridListItems;
}