Home > Back-end >  Flutter Column: how to put one button in the middle, and another at the bottom of the page?
Flutter Column: how to put one button in the middle, and another at the bottom of the page?

Time:12-14

This is the current alignment of two buttons

f

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:

enter image description here

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:

Column with two buttons example

  • Related