Stéphane de Luca
Stéphane de Luca

Reputation: 13583

How to center and shrink a row simultaneously within its parent?

I have a row with two component in as Card as follows:

Card(child:Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children:[
    Text("Col 1"),
    SizedBox(width: 10),
    Text("Col 2"),
  ])
)

Though the whole row content is horizontally centered in the screen, it expands the whole width where I'd like it to shrink to the space it really needs.

How to do that?

Upvotes: 0

Views: 42

Answers (2)

Ivo
Ivo

Reputation: 23178

Simply add

mainAxisSize: MainAxisSize.min,

to the Row. So like

Card(child:Row(
  mainAxisSize: MainAxisSize.min,
  mainAxisAlignment: MainAxisAlignment.center,
  children:[
    Text("Col 1"),
    SizedBox(width: 10),
    Text("Col 2"),
  ])
)

Upvotes: 1

matiboy212121
matiboy212121

Reputation: 101

Using the Expanded widget seems like your best bet, as it will shrink the row whilst ensuring that it's aligned in the center.

Card(
  child: Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Expanded(
        flex: 1,
        child: Text("Col 1"),
      ),
      SizedBox(width: 10),
      Expanded(
        flex: 1,
        child: Text("Col 2"),
      ),
    ],
  ),
)

Upvotes: 0

Related Questions