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

Time:01-24

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?

CodePudding user response:

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"),
      ),
    ],
  ),
)

CodePudding user response:

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"),
  ])
)
  • Related