'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:
Solution 1:[1]
Try to wrap your Container with Center. Center -> Container
Solution 2:[2]
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,
),),
)
Solution 3:[3]
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,
),)
Solution 4:[4]
Wrap the text with Center(). Or use mediaquery like:
height: MediaQuery.of(context).size.height / 0.5 inside SizedBox()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vaidarbhi |
| Solution 2 | Anmol Mishra |
| Solution 3 | Saiful Islam |
| Solution 4 | ouflak |





