Flutter:focused_menu显示时隐藏子图标问题求助
要实现菜单展开时隐藏原操作图标,你需要手动维护菜单的展开状态,再根据状态控制图标的显示,具体方案如下:
核心思路
FocusedMenuHolder本身没有直接暴露菜单展开状态,但提供了onMenuOpen和onMenuClose回调,我们可以通过这两个回调更新自定义的状态变量,再基于这个变量控制图标的显示/隐藏(或替换为透明占位,避免AppBar布局跳动)。
修改后的代码
class TestMenu extends StatefulWidget { const TestMenu({Key? key}) : super(key: key); @override State<TestMenu> createState() => _TestMenuState(); } class _TestMenuState extends State<TestMenu> { // 维护菜单展开状态 bool _isMenuOpen = false; @override Widget build(BuildContext context) { return FocusedMenuHolder( menuWidth: MediaQuery.of(context).size.width * 0.5, blurBackgroundColor: Colors.transparent, blurSize: 0, menuOffset: -50, openWithTap: true, // 菜单展开时更新状态 onMenuOpen: () { setState(() { _isMenuOpen = true; }); }, // 菜单收起时重置状态 onMenuClose: () { setState(() { _isMenuOpen = false; }); }, // 根据状态控制图标显示:展开时用透明占位,收起时显示原图标 child: _isMenuOpen ? const SizedBox( width: 24, // 和图标宽度保持一致,避免布局跳动 height: 24, ) : const Icon( Icons.more_vert, color: Colors.black, ), onPressed: () {}, menuItems: [ FocusedMenuItem( title: Row(children: [ const Icon( Icons.science, color: Colors.white, ), const SizedBox(width: 12), const Text( "Lab", style: TextStyle( color: Colors.white, ), ), ]), backgroundColor: Colors.blue, onPressed: () { print("Lab clicked"); }, ), FocusedMenuItem( title: Row(children: [ const Icon( Icons.settings, color: Colors.black, ), const SizedBox(width: 12), const Text( "Settings", style: TextStyle( color: Colors.black, ), ), ]), onPressed: () { print("Settings clicked"); }, ), FocusedMenuItem( title: Row(children: [ const Icon( Icons.share, color: Colors.black, ), const SizedBox(width: 12), const Text( "Share", style: TextStyle( color: Colors.black, ), ), ]), onPressed: () { print("Share clicked"); }, ), ], ); } }
为什么之前的方法无效?
- 修改
offset参数仅能调整菜单的位置,不会影响原操作图标的显示状态; - 用
Visibility包裹整个FocusedMenuHolder会导致菜单和图标同时被隐藏,因为菜单是FocusedMenuHolder的子组件,Holder不可见时菜单也会被隐藏。
内容的提问来源于stack exchange,提问作者Seth
相关产品推荐
相关产品推荐

