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

Flutter中如何让堆叠的两个组件同时响应光标悬停事件?

解决Flutter Stack中上层组件悬停事件传递给下层组件的问题

你当前的代码里,绿色容器的MouseRegion设置了hitTestBehavior: HitTestBehavior.translucent,但因为绿色容器本身是不透明的,它依然会拦截悬停事件,导致下方红色容器的onHover无法触发。要实现上层组件触发自身悬停逻辑的同时,让下层组件也响应,有两种直接的解决方式:

方法一:手动转发悬停事件

把红色容器的悬停逻辑提取为独立方法,在绿色容器的onHover中同时调用这个方法:

Stack(
  children: [
    Center(
      child: MouseRegion(
        onHover: _onRedHover,
        child: Container(
          height: 300,
          width: 300,
          color: Colors.red,
        ),
      ),
    ),
    Center(
      child: MouseRegion(
        hitTestBehavior: HitTestBehavior.translucent,
        onHover: (event) {
          debugPrint('Green: ${event.position}');
          _onRedHover(event); // 手动转发事件给红色容器的处理逻辑
        },
        child: Container(
          height: 200,
          width: 200,
          color: Colors.green,
        ),
      ),
    ),
  ],
)

// 提取红色容器的悬停处理方法
void _onRedHover(PointerHoverEvent event) {
  debugPrint('Red: ${event.position}');
}

方法二:使用Listener监听指针事件(更灵活的全局处理)

如果需要更复杂的事件传递逻辑,可以用Listener代替MouseRegion,利用PointerHoverEvent的传递特性,配合HitTestBehavior.translucent让事件向下穿透:

Stack(
  children: [
    Center(
      child: Listener(
        behavior: HitTestBehavior.translucent,
        onPointerHover: (event) {
          debugPrint('Red: ${event.position}');
        },
        child: Container(
          height: 300,
          width: 300,
          color: Colors.red,
        ),
      ),
    ),
    Center(
      child: Listener(
        behavior: HitTestBehavior.translucent,
        onPointerHover: (event) {
          debugPrint('Green: ${event.position}');
        },
        child: Container(
          height: 200,
          width: 200,
          color: Colors.green,
        ),
      ),
    ),
  ],
)

注意:Listener的behavior: HitTestBehavior.translucent会允许事件向下传递,所以当悬停在绿色容器上时,两个Listener的onPointerHover都会被触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:29:58