Home > Software design >  How can I center Text in stack?
How can I center Text in stack?

Time:12-21

I have a Stack that has two children. An Icon and a Text. The Icon is larger in height than the text, and dictates the height of the Stack. I would like the Text to center in the stack regardless of the size of the Icon.

Stack(
    children: [
      Align(
        alignment: Alignment.topRight,
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => Navigator.of(context).pop(),
          child: Padding(padding: EdgeInsets.all(4), child: Icon(Icons.close)),
        ),
      ),
      Center(
        child: Text(
          widget.title,
          textAlign: TextAlign.center,
        ),
      ),
    ],
  ),

With this current layout, the Text always draws at the top center of the stack, regardless of how Large the icon is. How can I correct this?

CodePudding user response:

Use Stack's alignment: Alignment.center to align the children.

The default value for 'alignment' is AlignmentDirectional.topStart.

Stack(
  alignment: Alignment.center,
  children: [
    const Text(
      "widget.title",
      textAlign: TextAlign.center,
    ),
    Align(
      alignment: Alignment.topRight,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => Navigator.of(context).pop(),
        child: Padding(
            padding: EdgeInsets.all(4), child: Icon(Icons.close)),
      ),
    ),
  ],
),

More about enter image description here

  • Related