Search code examples
fluttercenteringflutter-layoutword-wrap

Center row content, or wrap if it's too long


I have a Row with an Icon and a Text. I want the content of the Row to be centered, i.e. the Icon + Text should be centered, with the Icon to the left of the Text. I'm doing this by setting mainAxisAlignment: MainAxisAlignment.center on the Row.

The problem is that sometimes the content of the Text is too long to fit on one line, and needs to be wrapped. I can do this by wrapping it in an Expanded, but this also has the side effect of making the Text occupy the entire Row, so now the Icon and Text will become left-adjusted instead of centered in the Row, even if the text content is short.

Row(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.center,
    children: <Widget>[
        Icon(Icons.info_outline, color: Colors.grey),
        Expanded(
          child: Text(
              'Short text' // or 'Some very long text that won\'t fit one one line here'
          ),
        ),
    ],
)

How can I achieve what I want - i.e. centering the content of the Row while still allowing the Text to wrap if the text is too long to fit on one line?


Solution

  • If your Row is wrapped by Center.Try this.

    Center(
        child: Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
                Icon(Icons.info_outline, color: Colors.grey),
                Flexible(
                    child: Text('Hello World'),
                ),
            ],
        ),
    )
    

    Change Expanded to Flexible