Search code examples
flutterflutter-row

How to vertically center an Icon relative to a Text widget in Flutter?


I'm trying to display a header in Flutter where the Icon is aligned to the center of the Text widget's height. Here's the widget structure I have so far:

//dart

Widget header() {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(
        "Welcome back",
        style: TextStyle(
          fontSize: 20,
        ),
      ),
      Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            "User name",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 22,
              fontWeight: FontWeight.bold,
            ),
          ),
          Icon(
            kVerifiedIcon,
            color: kPrimaryColor,
            size: 15,
          ),
        ],
      ),
    ],
  );
}

Result:

enter image description here

Currently, the Icon appears slightly misaligned relative to the Text. I want the Icon to be vertically centered according to the height of the Text.

I've tried adjusting the size of the Icon and changing the crossAxisAlignment property in the Row, but it didn't work as expected.


Solution

  • In your provided code, the icon is centered within the Row, but it requires a slight padding from the top to align the icon vertically with the text. Try below code...

        Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Welcome back',
                style: TextStyle(
                  fontSize: 20,
                ),
              ),
              Row(
                children: [
                  Text(
                    'User name',
                    style: TextStyle(
                      fontSize: 22,
                    ),
                  ),
                  SizedBox(width: 5),
                  Container(
                    padding: EdgeInsets.only(top: 2),
                    child: Icon(
                      Icons.verified_rounded,
                      size: 15,
                    ),
                  ),
                ],
              ),
            ],
          ),