Home > Software design >  How to make a widget maximum size be equal to the flex value in a row
How to make a widget maximum size be equal to the flex value in a row

Time:02-09

I have this small code:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),

which renders into this:

enter image description here

Notice how the long text is wrapped even though there is still space around the small text.

I would like the small text to only take the size it needs to let the long text take the rest. And if the small text becomes bigger, its maximum size would be the size of the Flexible widget in the row (half of the Row in my example since both Expanded and Flexible have flex: 1).

If the small text is small enough, it should look like:

| Red text that can be long long long long | Small text |
| long                                     |            |

And if the "small" text is long too:

| Red text that can be long | Small text that is also  |
| long long long long       | very long                |

Is there a way to do that?

CodePudding user response:

You can use ConstrainedBox:constraints: BoxConstraints.loose( Size.fromWidth(maxWidth / 2) for green.

body:LayoutBuilder( 
  builder: (context, constraints) => Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text(
              'Red text that can be long long long lbe long long long lbe long long long long long'),
        ),
      ),
      ConstrainedBox(
        constraints: BoxConstraints.loose(
            Size.fromWidth(constraints.maxWidth / 2)),
        child: Container(
          color: Colors.green,
          child: const Text('Smalled g long th xt'),
        ),
      ),
    ],
  ),
),

CodePudding user response:

    Container(
    color: Colors.green,
    child: Row(
    children: [
     Expanded(
      flex: 1,
      child: Container(
        width: MediaQuery.of(context).size.width * 0.50,
        decoration: BoxDecoration(color: Colors.blue),
      ),
      ),
     Expanded(
      flex: 1,
      child: Container(
        width: MediaQuery.of(context).size.width * 0.50,
        decoration: BoxDecoration(color: Colors.red),
        ),
       ),
     ],
    ),
    ),
  •  Tags:  
  • Related