6

How to crop text depending on available space?

There's a similar question here, but there's no working answer.

Currently, this code

            return new GridTile(
              child: new Card(
                elevation: 3.0,
                child: new Container(
                  padding: new EdgeInsets.all(10.0),
                  child: new Column(
                    children: <Widget>[
                      Text(
                        document['title'],
                        style: new TextStyle(fontWeight: FontWeight.bold),
                      ),
                      Text(
                        document['text'],
                      ),
                    ],
                  ),
                ),
              )
            );

Gives this result:

enter image description here

I tried using overflow: TextOverflow.ellipsis, but the text becomes 1 line long. Specifying the text line length is a bad idea, because on different screen sizes results will vary.

How to make so that the text crops, fits or wraps itself into available space?

Darkhan
  • 2,888
  • 5
  • 20
  • 30

3 Answers3

10

Setting overflow behavior should do

  new Text(
    widget.text,
    // softWrap: true,
    overflow: TextOverflow.fade,
  )

See also Flutter: How to hide or show more text within certain length

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • tried overflow: TextOverflow.fade, but nothing has changed, the bottom is still overflowed by 88 pixels – Darkhan Apr 19 '18 at 05:54
  • Is the overflow actually from the `Text` widget, or is it from one of the parents? – Günter Zöchbauer Apr 19 '18 at 05:57
  • 2
    https://github.com/flutter/flutter/issues/15465#issuecomment-382458700 looks similar to what you seem to try to accomplish, perhaps it contains something helpful. – Günter Zöchbauer Apr 19 '18 at 06:36
  • 2
    @GünterZöchbauer it works but you need to add `maxLines: 1` too to your `Text`. But the problem is it fades the text vertically, I was looking for horizontal. Can you help? EDIT: Setting `softWrap: false` seems to work. – CopsOnRoad Nov 13 '18 at 17:59
5

Wrap the text widget Inside Expanded or Flexible widget and use overflow.ellipsis this worked for me

Column(
    children: <Widget>[
         Flexible(
             child: Text(
             "Some Very long Text or random generated strings ",
             overflow: TextOverflow.ellipsis,
             softWrap: true,
             ),
        ),
    ],
 ),
0

Try it:

extension StringX on String {
  String get overflow => Characters(this)
  .replaceAll(Characters(''), Characters('\u{200B}'))
  .toString();
}


Text(
 textString.overflow,
 overflow: TextOverflow.ellipsis,
 maxLines: 1,
)

It works for me.

source: https://github.com/flutter/flutter/issues/18761#issuecomment-812390920

Quyen Anh Nguyen
  • 1,204
  • 13
  • 21