简体   繁体   中英

Flutter text widget not centered

I am trying to have text centered inside a container. No matter what I did, text is never centered. Here is my code:

Container(
  alignment: Alignment.center,
  width: 47,
  height: 47,
  decoration: BoxDecoration(color: Colors.grey, shape: BoxShape.circle),
  child: Text(
    firstName == null && lastName == null
        ? 'UU'
        : '${firstName[0]}${lastName[0]}'.toUpperCase(),
    style: TextStyle(
      fontFamily: 'AvenirLTStd-Roman',
      fontSize: 18,
      color: Colors.white,
      fontWeight: FontWeight.w300,
    ),
    textAlign: TextAlign.center,
  ),
)

And this is how the screen is generated:

在此处输入图像描述

If you notice text is not centered, the bottom part of the container seems to have more "free space" compared to the top. When I open this in widget inspector and highlight Text Widget I see this:

在此处输入图像描述

Does anyone know what am I missing here and why is text not centered? I want text to be in the middle of the container and have equal space between top and bottom.

UPDATE:

Using Center widget does not help:

在此处输入图像描述

Try to wrap your Container with Center. Center -> Container

Wrap the text with Center(). This might be works.

Simply do this

Container(
  alignment: Alignment.center,
  width: 47,
  height: 47,
  decoration: BoxDecoration(color: Colors.grey, shape: BoxShape.circle),
  child: Center(child: Text(
    firstName == null && lastName == null
        ? 'UU'
        : '${firstName[0]}${lastName[0]}'.toUpperCase(),
    style: TextStyle(
      fontFamily: 'AvenirLTStd-Roman',
      fontSize: 18,
      color: Colors.white,
      fontWeight: FontWeight.w300,
    ),
    textAlign: TextAlign.center,
  ),),
)

Try to

Container(
      alignment: Alignment.center,
      width: 47,
      height: 47,
      decoration: BoxDecoration(color: Colors.grey, shape: BoxShape.circle),
      child: Center(child: Text(
        firstName == null && lastName == null
            ? 'UU'
            : '${firstName[0]}${lastName[0]}'.toUpperCase(),
          style: TextStyle(
          fontFamily: 'AvenirLTStd-Roman',
          fontSize: 18,
          color: Colors.white,
          fontWeight: FontWeight.w300,
        ),
        textAlign: TextAlign.center,
      ),),
    )

在此处输入图像描述

Try Like this

Container(
  alignment: Alignment.center,
  height: 47,
  width: 47,
  decoration: BoxDecoration(color: Colors.grey, shape: BoxShape.circle),
  child: Text(
  'UU',
  style: Theme.of(context).textTheme.headline6,
),)

图片

Please remove or change fontFamily it will fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM