flutterword-wrapiconbutton

Avoiding long word breaks


I have an icon button with an icon and the title. The title of the button is coming from API which is a combination of two words or sometimes more than two words. i.e Chinese Restaurants or Mexican restaurants. Sometimes, it breaks the word Restaurant if the name is too big and other time it also breaks the name as well. So is there any way to fix that so that I can see the full name without breaking the word? I tried using it.

textOverflow: TextOverflow.ellipsis,

and also tried max line to two/three. but I am not getting the desired result.
on large screen its working fine i am having problems only on small devices.

Any help or suggestions on that? thanks.

IconButton(
    icon:  Icon(Icon.resutaurant),
    title: restaurantname,
    textOverflow: TextOverflow.ellipsis,
    onPressed: () {},
),

Solution

  • If the text is too long for the available space, you will need to decrease the font size. This can be done manually via calculating the necessary space with a TextPainter, or you can chose a readily available package such as auto_size_text to manage that for you.

    In its most basic form, it can be used like this

    AutoSizeText(
      'A really long String',
      style: TextStyle(fontSize: 30),
      maxLines: 2,
    )
    

    The style argument is used to set the font when enough space is available. A "target font size" if you want to call it that way.

    There are a lot of customisation options that are illustrated in the Github repository.

    The animation below taken from above-linked GitHub repo gives a nice visual representation of the effect that auto sizing has on your text. When it comes to the UX question of text truncation vs font size adaption, this question can serve as an introduction to the topic.

    enter image description here