I want to create a widget that takes a list of widgets (in this case always buttons) and automatically arranges them in a kind of grid depending on the width of the child.
When there are 2 Buttons in a row, each button should have 50% of the width. So it should be something like this:
First i tried this Code:
Widget getOrderedButtonList(
List<Widget> buttonList,
) {
final List<Widget> orderedButtonList = [];
for (int index = 0; index < buttonList.length; index = index + 2) {
orderedButtonList.add(
Row(
children: [
Expanded(child: buttonList[index]),
if (index + 1 < buttonList.length) HmipSpacer.horizontal(),
if (index + 1 < buttonList.length) Expanded(child: buttonList[index + 1]),
],
),
);
}
return Column(
children: orderedButtonList,
);
}
This works fine for buttons with small text, but when the text is longer i have the problem, that the text wont fit in the button like this:
I dont want to show the text in multiple lines (would be the easiest solution). So I need a solution where a button is placed in a new row if the text doesn’t quite fit.
I tried the flex_list library which can arrange a list of widgets depending on their width and it looked like this:
That’s almost what I want. The 3 buttons in a row aren’t bad either. However, the buttons now all have a different width. I want the buttons to always have the same width and as soon as that no longer fits, they are wrapped.
So in this example it should look like this:
Does anyone know how to do this?
2
Answers
The answer from @MaLa would work with a little refactoring, but I've already found another solution. I changed the performlayout method in the flex_list library a bit so that all elements in a row have the same width. If someone needs this too, here is the code:
I found this
method from How to check if Flutter Text widget was overflowed.
In this implementation, we check does the widget fit the space or does it overflow. We also have to check does it make the previous widgets in the row overflow. If not, then we add the item into the row. If yes then we create a new row.
This code needs some refactoring and also I have not tested how it works with paddings.
The output of this code looks like this: