Search code examples
flutterflutter-layout

How to center only one element in a row of 2 elements in flutter


In my layout I have two Widgets in a row, one text and the an icon.

As shown below, assume that * refers to the icon, and using "-" to represent the row:

----------------------------
           Text          *  
----------------------------

How do I make my text centered in the entire row, and the icon to the right end ?


Solution

  • The main thing you need to notice is that if you don't want to use Stack you should provide same width-consuming widgets both on left and right.

    I would do this with either Expanded and Padding

    Row(
      children: <Widget>[
        Expanded(
          child: Padding(
            padding: const EdgeInsets.only(left: 32.0),
            child: Text(
              "Text",
              textAlign: TextAlign.center,
            ),
          ),
        ),
        Icon(Icons.add, size: 32.0,)
      ],
    )
    

    or with Row's mainAxisAlignment and a SizedBox

    Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        const SizedBox(width: 32.0),
        Text("Text"),
        Icon(Icons.add, size: 32.0)
      ],
    )
    

    or with Expanded and a SizedBox on the left instead of the padding :). The padding or extra container on the left is so that the textAlign will truly center the text in the row taking into account the space taken up by the Icon.