如何相对于中心在 Stack 中定位小部件?

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'),
      ),
  ],
),

我正在尝试相对于中心在 Stack 中定位小部件。

上面代码中的???如何得到?

这是一种方法

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

您需要使用 LayoutBuilder 小部件,它会在布局时构建并提供父小部件的约束。

试试

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

您可以使用这种方法使您的 Text() 居中,因为您不能指定 Text() 的宽度,因为宽度在每个 Text() 情况下都不是常量。

 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')
        ]
      ),
    ),
  ],
),