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

Flutter项目中如何实现NavigationRail鼠标悬停展开功能?

解决方案

要实现NavigationRail鼠标悬停展开的功能,你需要通过MouseRegion组件监听鼠标的进入/离开事件,结合状态变量来控制extended属性,替代原代码中仅依赖屏幕宽度的逻辑。以下是修改后的关键代码:

class _MyHomePageState extends State<MyHomePage> {
  var selectedIndex = 0;
  bool _isHovering = false; // 新增状态变量跟踪鼠标悬停状态

  @override
  Widget build(BuildContext context) {
    Widget page;
    switch (selectedIndex) {
      case 0:
        page = GeneratorPage();
        break;
      case 1:
        page = Placeholder();
        break;
      default:
        throw UnimplementedError('no widget for $selectedIndex');
    }

    return LayoutBuilder(builder: (context, constraints) {
      return Scaffold(
        body: Row(
          children: [
            SafeArea(
              // 用MouseRegion包裹NavigationRail,监听悬停事件
              child: MouseRegion(
                onEnter: (_) => setState(() => _isHovering = true),
                onExit: (_) => setState(() => _isHovering = false),
                child: NavigationRail(
                  // 宽屏时保持展开,小屏时仅悬停展开(可根据需求调整逻辑)
                  extended: constraints.maxWidth >= 600 || _isHovering,
                  destinations: [
                    NavigationRailDestination(
                      icon: Icon(Icons.home),
                      label: Text('Home'),
                    ),
                    NavigationRailDestination(
                      icon: Icon(Icons.favorite),
                      label: Text('Favorites'),
                    ),
                    NavigationRailDestination(
                      icon: Icon(Icons.person),
                      label: Text('Profile'),
                    ),
                  ],
                  selectedIndex: selectedIndex,
                  onDestinationSelected: (value) {
                    setState(() {
                      selectedIndex = value;
                    });
                  },
                ),
              ),
            ),
            Expanded(
              child: Container(
                color: Theme.of(context).colorScheme.primaryContainer,
                child: page,
              ),
            ),
          ],
        ),
      );
    });
  }
}

修改说明

  • 新增_isHovering变量,用于记录鼠标是否处于NavigationRail区域内
  • 通过MouseRegion的onEnter和onExit回调,实时更新悬停状态
  • 调整extended属性的判断逻辑:屏幕宽度≥600时始终展开,小屏模式下仅在鼠标悬停时展开(若不需要宽屏自动展开,可直接将extended设为_isHovering)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:32:02