skip to Main Content

I want to vertically and horizontally center a text within a white container in flutter.

Code I used to generate the following example but it is not vertically centered. Any idea how to?

return Center(
  child: Container(
    color: Colors.white,
    width: 105,
    height: 105,
    child: Align(
      alignment: Alignment.center,
      child: Container(
        color: Colors.green,
        child: Text(
          '1',
          style: TextStyle(fontSize: 100),
        ),
      ),
    ),
  ),
);

enter image description here

3

Answers


  1. you can use Center widget to align it center

    Center(
      child: Container(
        color: Colors.amberAccent,
        width: 105,
        height: 105,
        child: Center(
          child: Text(
                '1',
                style: TextStyle(fontSize: 20),
              ),
        ),
      ),
    )
    

    and you text is not center because fontSize is too large so decrease it

    Login or Signup to reply.
  2. Try this:

    Container(
          color: Colors.white,
          width: 105,
          height: 105,
          alignment: Alignment.center,
          child: Container(
            color: Colors.green,
            alignment: Alignment.center,
            child: Text(
              '1',
              style: TextStyle(fontSize: 100),
            ),
          ),
        );
    
    Login or Signup to reply.
  3. In your code, the Text widget is already centered vertically, but the text itself has some line height that makes it looks like there is some space on the top.

    From the documentation of height property of TextStyle:

    Text line height


    If you set the height to 1.1 for example, you can see it now looks centered:

    Text(
      '1',
      style: TextStyle(
        fontSize: 100,
        height: 1.1,
      ),
    )
    

    enter image description here


    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search