Home > Blockchain >  How properly center text in a container
How properly center text in a container

Time:08-06

I am trying to display some numbers inside some circular containers. Inside of the container I am using a center widget with the text as its child. However, as you can see in the image attached the text is very noticeably not centered. My code:

return SizedBox(
      height: 21,
      width: 21,
      child: DecoratedBox(
        decoration: BoxDecoration(
          color: MyColors.gray2,
          shape: BoxShape.circle,
        ),
        child: Center(
          child: Text(
            location.toString(),
            textScaleFactor: 1,
            style: positionTextStyle,
          ),
        ),
      ),
    );

Example image

CodePudding user response:

use textAlign: TextAlign.center,

child: Text(
  location.toString(),
  textAlign: TextAlign.center,
  textScaleFactor: 1,
  style: positionTextStyle,
),

Better with container

Container(
  height: 21,
  width: 21,
  alignment: Alignment.center,
  child: DecoratedBox(
    decoration: BoxDecoration(
      color: MyColors.gray2,
      shape: BoxShape.circle,
    ),
    child:  Text(
        "12",
        textAlign: TextAlign.center,
        textScaleFactor: 1,
        // style: positionTextStyle,
      ),
  ),
)

CodePudding user response:

You can manage size with padding which will eliminate the issue of text being overflowed and will keep the text in the center. Also you can use a single container and add decoration to it like

return Container(
      padding: EdgeInsets.all(5),
       decoration: BoxDecoration(
      color: MyColors.gray2,
       shape: BoxShape.circle,
       ),
        child:  Text(
            location.toString(),
            textScaleFactor: 1,
            style: positionTextStyle,
          ),
    );
  • Related