I would like to have a screen with a changeable amount of buttons. This is realized by a list of MaterialButtons. Because I don't know the amount of the buttons (maybe is too big to display all of them on the screen), I use a SingleChildScrollView to make the list of buttons scrollable. If there are less buttons, so that the screen is not filled completely, the buttons should always be displayed in the middle of the screen. At the moment, the button list always starts at the top of my screen.
Does anybody know how to implement this automatic position adjustment? And is it possible to change the space between the buttons?
This is my code (at the moment there is a fix number of 3 buttons but that will be changed soon):
class PlanState extends State<PlanForm> {
var namesList = new List<String>();
List<MaterialButton> buttonsList = new List<MaterialButton>();
@override
void initState() {
super.initState();
namesList.add("Button1");
namesList.add("Button2");
namesList.add("Button3");
List<Widget> _buildButtonsWithNames() {
int length = namesList.length;
for (int i = 0; i < length; i++) {
buttonsList
.add(new MaterialButton(
height: 40.0,
minWidth: 300.0,
color: Colors.blue,
textColor: Colors.white,
child: new Text(namesList[0], textScaleFactor: 2.0,),
onPressed: () {
Navigator.push(context, new MaterialPageRoute(builder: (context) => new viewPlanScreen()),);
}
));
namesList.removeAt(0);
}
return buttonsList;
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child:Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: _buildButtonsWithNames()
)
)
);
}
}
Because the SilgheChildScrollView has an "infinite" size in the main axis direction you can not center things like in other scenarios. If you check the documentation [1] there are some examples on how to achieve this like centering if there is enough room. I have no tried but should be something like this:
LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _buildButtonsWithNames(),
)
)
)
}
)
[1] https://api.flutter.dev/flutter/widgets/SingleChildScrollView-class.html