You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何将Widget置于居中Widget的上方?

解决方案

你的问题出在Stack的alignment: Alignment.center让蓝色容器和红色容器都居中重叠了。要让蓝色容器放在居中的红色容器上方,可采用以下两种方法:

方法一:用Positioned组件精准定位

直接在Stack中对蓝色容器进行定位,基于红色容器的位置调整间距:

body: Container(
  width: double.infinity,
  child: Stack(
    alignment: Alignment.center,
    children: [
      // 居中的红色容器
      Container(
        height: 100,
        width: 200,
        color: Colors.red,
      ),
      // 蓝色容器,定位在红色容器上方
      Positioned(
        bottom: 120, // 距离红色容器底部120(红色高度100,预留20间距)
        child: Container(
          height: 150,
          width: 100,
          color: Colors.blue,
        ),
      )
    ],
  ),
),

方法二:用Align组件结合偏移量

通过Alignment的偏移参数,让蓝色容器相对于Stack中心(即红色容器位置)向上偏移:

body: Container(
  width: double.infinity,
  child: Stack(
    alignment: Alignment.center,
    children: [
      Align(
        // 向上偏移,偏移量可根据容器高度自行调整
        alignment: Alignment(0, -0.8),
        child: Container(
          height: 150,
          width: 100,
          color: Colors.blue,
        ),
      ),
      Container(
        height: 100,
        width: 200,
        color: Colors.red,
      ),
    ],
  ),
),

关键说明

原代码中的Column完全多余——单个居中的红色容器直接放在Stack里即可。Stack的子组件按顺序堆叠,后添加的组件层级更高;如果需要蓝色在红色上方,要么调整组件顺序,要么用定位组件控制位置。

内容的提问来源于stack exchange,提问作者android dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 07:30:55