Search code examples
flutterdartflutter-layoutflutter-animation

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

  • 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,
                    ),
                  ),
                ],
              );
            },
          ),
        );
      }
    }