Search code examples
layoutflutter

In Flutter, how to use FittedBox to resize Text inside of a Row?


I have a row, with an icon at each side, and then a text with an icon in the middle:

@override
Widget build(BuildContext context) {
  return Row(
    children: [
      Icon(Icons.arrow_back),
      Expanded(child: SizedBox()),
      Icon(Icons.account_box),
      Text("Some Text Here ", maxLines: 1), // ➜ This is the text.
      Expanded(child: SizedBox()),
      Icon(Icons.arrow_forward),
    ],
  );
}

When the text gets big enough to fill the whole space, I want a FittedBox to make is smaller. So I tried this:

      FittedBox(child: Text("Some Text Here. More. More. More. More. More. More. More. More. ", maxLines: 1)), 

It doesn't work (it overflows). I believe the problem is that Row doesn't tell FittedBox the maximum size it could have. I have thought about using FittedBox with Expanded, IntrinsicWidth, UnconstrainedBox, Flexible and Align, to no avail.

How can I solve this?

Update: I wrote an article which would have helped me solve this problem: https://medium.com/flutter-community/flutter-the-advanced-layout-rule-even-beginners-must-know-edc9516d1a2


Solution

  • For what I understand you need to fit the text inside of the row, according to text length.

    Working Code:

    Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Icon(Icons.arrow_back),
        Expanded(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(Icons.account_box),
              Flexible(
                child: FittedBox(
                  fit: BoxFit.scaleDown,
                  child: Text(
                    "  Text HereSome Text Here Text HereSomext HereSome TText HereSome Text HereSome Text HereSome Text HereSome Text HereSome TText HereSome Text HereSome Text HereSome",
                    maxLines: 1,
                  ),
                ),
              )
            ],
          ),
        ),
        Icon(Icons.arrow_forward),
      ],
    );
    

    Output, long text:

    enter image description here

    Output, short text:

    enter image description here