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

Flutter Stack组件:无需调整子项顺序让红色Container居上层

在Flutter Stack中不调整子项顺序让红色Container显示在上层的方法

Flutter的Stack默认遵循子项越靠后,层级越高的规则,所以当前代码里绿色Container会覆盖在红色上方。要在不调整子项顺序的前提下让红色Container显示在上层,最直接的方式是利用定位组件的zIndex属性:

方法一:用Positioned包裹红色Container并设置zIndex

Positioned是Stack的定位子组件,支持通过zIndex控制层级(数值越大,层级越高,默认值为0)。给红色Container设置更高的zIndex即可让它压在绿色Container上方:

Stack(
  children:[
    Positioned(
      zIndex: 1, // 层级高于默认的0
      child: Container(
        color:Colors.red,
        width:200,
        height: 200,
      ),
    ),
    Container(
      color:Colors.green,
      width:200,
      height: 200,
    )
  ]
)

方法二:用其他定位组件(如Align)包裹并设置zIndex

如果不需要精准定位,只是想调整层级,也可以用Align、Center这类定位组件包裹红色Container,同样设置zIndex即可:

Stack(
  children:[
    Align(
      zIndex: 1,
      child: Container(
        color:Colors.red,
        width:200,
        height: 200,
      ),
    ),
    Container(
      color:Colors.green,
      width:200,
      height: 200,
    )
  ]
)

注意:只有Stack的定位类子组件(Positioned、Align、Center、Padding等能控制位置的组件)支持zIndex属性,直接放在Stack里的普通Container无法设置该属性。

内容的提问来源于stack exchange,提问作者Mohammed Hamdan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:15:36