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
相关产品推荐
相关产品推荐

