Is there a clean way to responsively abbreviate?

Let’s have a widget that includes a Text with a label, such as “MAXIMUM”. I’d like the widget to say “MAXIMUM” when there’s room for it, but to say “MAX” when there isn’t. It never goes below the width needed for “MAX” and never goes above the width needed for “MAXIMUM”.

I can build it (probably using a leaf render object?) but before I do, I wonder if there’s an elegant way to do it using regular widgets? Maybe I’m missing something obvious?

3 Likes

I had implemented something similar before, you dont need a leaf render object. I did have to make it stateful though

Internally in the component Im using a LayoutBuilder which gives constraints.
And then a construct a text painter like so

final textPainter = TextPainter(
      text: text,
      textAlign: widget.textAlign ?? TextAlign.left,
      textDirection: widget.textDirection ?? TextDirection.ltr,
      textScaleFactor: scale,
      maxLines: maxLines,
      locale: widget.locale,
      strutStyle: widget.strutStyle,
    );

Which after you have called textPainter.layout on will give you the width. So then you can just compare textPainter.width > constraints.maxWidth and decide to do something using that

4 Likes

Ah yes, that’s what I was looking for! Thank you.

2 Likes