'How to position widget inside Stack relative to center?

Stack(
  children: [  
      Positioned(
        left: ??? + 20,
        child: Text('This text is 20 pixel left to the center of the stack'),
      ),
  ],
),

I am trying to position widget inside Stack relative to center.

How to get ??? in the above code?



Solution 1:[1]

You will want to use the LayoutBuilder widget which will build at layout time and provides the parent widget's constraints.

demo

Try something like

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  double _constIconSize = 50;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          print(constraints);
          return Stack(
            children: <Widget>[
              //Exact center
              Positioned(
                top: constraints.constrainHeight() / 2 - _constIconSize / 2,
                left: constraints.constrainWidth() / 2 - _constIconSize / 2,
                child: Icon(
                  Icons.gps_fixed,
                  color: Colors.green,
                  size: _constIconSize,
                ),
              ),
              //100 right and 50  bottom from center
              Positioned(
                top: constraints.constrainHeight() / 2 + 100,
                left: constraints.constrainWidth() / 2 + 50,
                child: Icon(
                  Icons.face,
                  color: Colors.red,
                  size: _constIconSize,
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

Solution 2:[2]

Here is one way of doing it

     Positioned(
        left: MediaQuery.of(context).size.width / 2 + 20,
        child:
            Text('This text is 20 pixel left to the center of the stack'),
      ),

Solution 3:[3]

You can use this approch to center you Text() becuase you can not specify the width of your Text() as width is can not constant in every Text() cases.

 Stack(
  children: [
    Positioned(
      left: 0,
      right: 0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children:[
          Text('This text is 20 pixel left to the center of the stack')
        ]
      ),
    ),
  ],
),

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 Ajay Kumar
Solution 2 LonelyWolf
Solution 3 Hassan Mehmood