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

Flutter Web实现DropdownButton鼠标悬停展开功能的方法

Flutter Web实现DropdownButton鼠标悬停展开

Flutter自带的DropdownButton没有直接支持鼠标悬停展开的属性,我们可以通过MouseRegion监听鼠标事件,结合GlobalKey控制下拉菜单的显示,具体实现如下:

  1. 在你的State类中添加两个成员变量:

    final GlobalKey<DropdownButtonState<String>> _dropdownKey = GlobalKey();
    bool _isHovered = false;
    
  2. 用MouseRegion包裹原有DropdownButton,监听鼠标进出事件并控制菜单展开:

    MouseRegion(
      onEnter: (_) {
        setState(() => _isHovered = true);
        // 触发下拉菜单展开
        _dropdownKey.currentState?.showMenu();
      },
      onExit: (_) {
        setState(() => _isHovered = false);
        // 可选:鼠标离开时关闭菜单,若保留点击外部关闭的默认行为可忽略此句
        // _dropdownKey.currentState?.hideMenu();
      },
      child: DropdownButton(
        key: _dropdownKey, // 绑定GlobalKey
        value: teachingsDropdownValue,
        icon: SizedBox.shrink(),
        focusColor: Colors.white,
        elevation: 0,
        onTap: (){},
        underline: Container(
          height: 2,
          color: Colors.white,
        ),
        items: teachingsItems.map((String items) {
          return DropdownMenuItem(
            value: items,
            child: Text(items, textAlign: TextAlign.center,),
          );
        }).toList(),
        onChanged: (String? newValue) {
          setState(() {
            if(newValue == "Salivation"){
              Navigator.of(context).push(MaterialPageRoute(builder: (context) => TeachingsSalivationScreen()));
            }
          });
        },
      ),
    )
    
  3. 补充说明:

    • 确保你的组件是StatefulWidget,才能使用setState更新状态
    • 若需要鼠标离开下拉菜单区域时自动关闭,由于菜单是独立Overlay层,可能需要额外监听菜单区域的鼠标事件,或者保留默认的点击外部关闭逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:31:19