Flutter 设置小部件位置正好在屏幕中心

Flutter set widget position exactly center of the screen

我想在设备屏幕中间放置一个容器小部件。但是,由于我之前使用了 SizedBox()SvgPicture.asset() 小部件,因此容器不会出现在设备中间。我该怎么做?

这是我的代码:

class CenterWidget extends StatefulWidget {
  const CenterWidget({Key? key}) : super(key: key);

  @override
  _CenterWidgetState createState() => _CenterWidgetState();
}

class _CenterWidgetState extends State<CenterWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 30),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: [
              const SizedBox(height: 56),
              SvgPicture.asset(ImageConstants.instance.logoSvg,
                  width: (MediaQuery.of(context).size.width - 60) / 2),
              Expanded(
                child: Center(
                  child: Container(
                    color: Colors.red,
                    width: 100,
                    height: 100,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

使用顶部居中对齐的堆栈,并将您想要居中的小部件放在 Positioned.fill 小部件中。您可以将间隔符和徽标放在它们自己的列中以使其垂直排列:

class _CenterWidgetState extends State<CenterWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 30),
          child: Stack(
            alignment: Alignment.topCenter,
            children: [
              Column(
                children: [
                  const SizedBox(height: 56),
                  SvgPicture.asset(ImageConstants.instance.logoSvg,
                      width: (MediaQuery.of(context).size.width - 60) / 2),
                ],
              ),
              Positioned.fill(
                child: Center(
                  child: Container(
                    color: Colors.red,
                    width: 100,
                    height: 100,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}