This is the current alignment of two buttons
Code:
Widget build(BuildContext context) {
return Scaffold(
body: Align(
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
child: const Text('Button 1'),
onPressed: () {},
),
TextButton(
onPressed: () {},
child: const Text('Button 2'),
),
],
),
),
);
}
How can I place Button 2 at the very bottom of the page while keeping Button 1 at the center? Like this:
CodePudding user response:
Try this code:
Widget build(BuildContext context) {
return Scaffold(
body: Align(
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Spacer(),
ElevatedButton(
child: const Text('Button 1'),
onPressed: () {},
),
Spacer(),
TextButton(
onPressed: () {},
child: const Text('Button 2'),
),
],
),
),
);
}
CodePudding user response:
A Column
is a Flex widget that takes all the vertical space its parent gives it and then aligns its children based on its own and their constraints.
If you use an Expanded
widget as the first child of the column it will expand itself to take up all the available space, then you can nest your button at the center of that widget using a Center
widget.
The second button will only ask for as much vertical space as it needs to take, resulting on the layout that you wanted.
The full example below:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: SafeArea(
child: Column(
children: [
Expanded(
child: Center(
child: ElevatedButton(
child: const Text('Button 1'),
onPressed: () {},
),
),
),
TextButton(
child: const Text('Button 2'),
onPressed: () {},
)
],
),
),
);
}
The result: