Home > OS >  Horizontally centering Text widget inside Stack
Horizontally centering Text widget inside Stack

Time:07-27

I need to center a Text widget inside a Stack widget.

This is my code for the Text widget:

 Positioned(
          top: alturaFondo   alturaAvatar/2,

          child:  Padding(
              padding: const EdgeInsets.all(8.0),
              child:
                  Text("username", textAlign: TextAlign.center, style: TextStyle(fontSize: 18,color: Colors.black54),)

              ),
            ),

I have tried putting the Text inside an Align widget, but not centering it either.

CodePudding user response:

You can do it like this

Stack(
  children: [
    Positioned.fill(
      child: Center(
        child: Text('centered'),
      ),
    )
  ],
)

CodePudding user response:

With Positioned(left:0,right:0) just horizontal-center

body: Stack(
  children: [
    Positioned(
      left: 0,
      right: 0,
      child: Text(
        "username",
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18, color: Colors.black54),
      ),
    ),
  ],
),

You can use just Center

Stack(
  children: [
    Center(
      child: Text(
        "username",
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18, color: Colors.black54),
      ),
    ),
  ],
),

with Aling widget,

Stack(
  children: [
    Align(
      alignment: Alignment.center,// default also center
      child: Text(
        "username",
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18, color: Colors.black54),
      ),
    ),
  ],
),
  • Related