How can I center 2 or more widgets(Screen) in Flutter?

Issue

I want to center 2 Buttons and Text in the center of the screen.
I want something like that,
enter image description here

I am using this code :

body: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$_counter',
              style: TextStyle(
                  fontSize: 40.0,
                  fontFamily: 'Hero',
                  fontWeight: FontWeight.bold),
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    _counter += 1;
                  });
                },
                child: Text('Increment')),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    _counter -= 1;
                  });
                },
                child: Text('Decrement'))
          ],
        ),
      ],
    ),

I am now using Both Row and Column widget and setting MainAxisAlignment to Center. I guess this is not an efficient way to do this.

I tried this one code as shown on other stackoverflow Question (using CrossAxisAlignment)

body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Text(
          '$_counter',
          style: TextStyle(
              fontSize: 40.0,
              fontFamily: 'Hero',
              fontWeight: FontWeight.bold),
        ),
        ElevatedButton(
            onPressed: () {
              setState(() {
                _counter += 1;
              });
            },
            child: Text('Increment')),
        ElevatedButton(
            onPressed: () {
              setState(() {
                _counter -= 1;
              });
            },
            child: Text('Decrement'))
      ],
    ),

But this code is not working the way I want! It is showing me something like this.
enter image description here

Any solution ?
Thanks in advance 🙂

Solution

Wrap your column with Center.

body:Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[

Answered By – Yeasin Sheikh

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.