ych
ych

Reputation: 2075

How to make widgets in a row the same width as the widest from them

For example, we have next widget:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        OutlinedButton(
          child: Text('B 1'),
          onPressed: () {},
        ),
        OutlinedButton(
          child: Text('BB 2'),
          onPressed: () {},
        ),
        OutlinedButton(
          child: Text('BBBBB 5'),
          onPressed: () {},
        ),
      ],
    );
  }
}

How can we create all buttons ('B1' and 'BB 2') to have the same width as the widest last one ('BBBBB 5'). So resulting MyWidget width will be the width of 'BBBBB 5' button multiply 3.

And yes, text on buttons can vary; that is why we can't precalculate and hardcode their width.

Upvotes: 6

Views: 2453

Answers (1)

Miguel Ruivo
Miguel Ruivo

Reputation: 17756

You need to combo IntrinsicWidth with any Flex widget, such as Expanded here.

If you wrap all of your children with an Expanded, you'll end up sharing evenly the space between them all, the thing is that you actually don't want that because eventually you will have a Row filling all the available space with 3 buttons with a lot of "white" space.

Because you want the buttons to all have the exactly same width as the bigger sibling, you first will have to wrap each child with an Expanded widget and then wrap the Row with an IntrinsicWidth widget, which will force all the children to share the width of the bigger one.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return IntrinsicWidth(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Expanded(
            child: OutlinedButton(
              child: Text('B 1'),
              onPressed: () {},
            ),
          ),
          Expanded(
            child: OutlinedButton(
              child: Text('BB 2'),
              onPressed: () {},
            ),
          ),
          Expanded(
            child: OutlinedButton(
              child: Text('BBBBB 5'),
              onPressed: () {},
            ),
          )
        ],
      ),
    );
  }
}

enter image description here

Upvotes: 9

Related Questions