Stefan
Stefan

Reputation: 382

How to strech a column while centering their children

I want to expand a column horizontally while keeping the children (an icon and a text) in the center.

When I use CrossAxisAlignment.center it doesn't mathes its parents width. So I tried CrossAxisAlignment.stretch.

Column(
  crossAxisAlignment: CrossAxisAlignment.stretch,
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Icon(Icons.help),
    Text('Please help!'),
  ],
),

Here the text was aligned left even though the icon is centerd. I do not understand this and a solution would be highly appreciated.

Upvotes: 2

Views: 670

Answers (4)

CopsOnRoad
CopsOnRoad

Reputation: 267404

The right way to do is:

Center( // it helps column stretch
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center, // it helps child stay in center
    children: ...,
  )
)

Upvotes: 0

Claudio Castro
Claudio Castro

Reputation: 1569

Another way.

Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: Container(),
            ),
            Icon(
              Icons.help,
              color: Colors.white,
            ),
            Expanded(
              child: Container(),
            ),
          ],
        ),
        Row(
          children: <Widget>[
            Expanded(
              child: Container(),
            ),
            Text('Please help!'),
            Expanded(
              child: Container(),
            ),
          ],
        )
      ],
    )

Upvotes: -1

nmanikiran
nmanikiran

Reputation: 3148

I found a hack might not the exact solution but works for me.

there might be other solutions

Added a SizedBox box widget with width because we need to center horizontally.

Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(Icons.help),
            Text('Please help!'),
            SizedBox(
              width: double.infinity, // it will take entire available device width
              height: 0,
            )
          ],
        ),

Upvotes: 1

lino alejandro
lino alejandro

Reputation: 485

have you tried wrapping column in a container and setting width to double.infinity?

Container(
    width: double.infinity,
    child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
            Icon(Icons.help),
            Text('Please help!'),
        ],
    ),
)

Upvotes: 1

Related Questions