Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vertically centering an overflowing widget

I have a bit of user generated content that is restricted to a specific height. Anything over that height should be overflowing and clipped off.

I’ve achieved that by wrapping the content with a Wrap widget, however the extra requirement i have is that the overflowed content should always be centered in its parent, see image below

Image

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The current behaviour is the first red box, but what I’m looking for is to vertically center the content similarly to box #2

Example code I’ve used is:

Container(
      constraints: BoxConstraints(minHeight: 40, maxHeight: 40),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.red,
      ),
      clipBehavior: Clip.hardEdge,
      child: Wrap(
        children: [
          Column(
            children: [
              Text('Line1'),
              Text('Line2'),
              Text('Line3'),
              Text('Line4'),
              Text('Line5'),
              Text('Line6'),
              Text('Line8'),
              Text('Line9'),
              Text('Line10'),
            ],
          ),
        ],
      ),
    )

I’ve tried the various alignment properties the Wrap widget offers, however none of them did the trick. Is there a specific flutter widget I can use to achieve this?

>Solution :

You can use a FittedBox (https://api.flutter.dev/flutter/widgets/FittedBox-class.html) with BoxFit.none (https://api.flutter.dev/flutter/painting/BoxFit.html#none) to center the child in the available space while clipping everything outside.

Container(
  constraints: BoxConstraints(minHeight: 40, maxHeight: 40),
  alignment: Alignment.center,
  decoration: BoxDecoration(
    color: Colors.red,
  ),
  clipBehavior: Clip.hardEdge,
  child: FittedBox(
    fit: BoxFit.none,
    child: Column(
      children: [
        Text('Line4'),
        Text('Line5'),
        Text('Line6'),
        Text('Line8'),
        Text('Line9'),
        Text('Line10'),
      ],
    ),
  ),
),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading