Flutter多可交互FAB实现问题:展开子按钮无法点击
问题解决:Flutter折叠FAB子按钮无法点击
问题原因
你当前代码里,Stack的children列表中主FAB放在最后,按照Flutter的渲染规则,Stack中后添加的widget会覆盖在前面的widget之上。所以即便子FAB通过动画移动到了主FAB的视觉上方,实际的点击区域还是被主FAB占据,导致子按钮无法响应点击事件。
修复方案
把主FAB移到Stack的children列表最前面,这样动画展开后的子FAB会处于主FAB的上层,就能正常接收点击事件了。
修改后的完整代码
class _PageScreenState extends ConsumerState<PageScreen> with TickerProviderStateMixin { late ShoppingList shoppingList; late AnimationController _controller; late Animation<Offset> _offsetAnimation1; late Animation<Offset> _offsetAnimation2; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 250), vsync: this, ); _offsetAnimation1 = Tween<Offset>( begin: Offset.zero, end: Offset(0.0, -1.5), ).animate(CurvedAnimation( parent: _controller, curve: Curves.easeInOut, )); _offsetAnimation2 = Tween<Offset>( begin: Offset.zero, end: Offset(-1.0, -1.0), ).animate(CurvedAnimation( parent: _controller, curve: Curves.easeInOut, )); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { int index = ModalRoute.of(context)!.settings.arguments as int; return Scaffold( floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: Padding( padding: const EdgeInsets.only(bottom: 16.0), child: Stack( alignment: Alignment.bottomCenter, children: [ // 主FAB移至列表最前端 FloatingActionButton( backgroundColor: Colors.white, onPressed: () { if (_controller.isDismissed) { _controller.forward(); } else { _controller.reverse(); } }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(100), side: BorderSide(color: Theme.of(context).colorScheme.primary), ), child: Icon(Icons.menu, color: Theme.of(context).colorScheme.primary), ), SlideTransition( position: _offsetAnimation1, child: FloatingActionButton( heroTag: 'qrButton', backgroundColor: Colors.white, onPressed: () { print("QR Button Pressed"); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(100), side: BorderSide(color: Theme.of(context).colorScheme.primary), ), child: Icon(Icons.qr_code, color: Theme.of(context).colorScheme.primary), ), ), SlideTransition( position: _offsetAnimation2, child: FloatingActionButton( heroTag: 'addButton', backgroundColor: Colors.white, onPressed: () { print("Add Button Pressed"); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(100), side: BorderSide(color: Theme.of(context).colorScheme.primary), ), child: Icon(Icons.add, color: Theme.of(context).colorScheme.primary), ), ), ], ), ), body: const Text("Text"), ); } }
额外优化建议
- 给主FAB添加图标旋转动画(比如从菜单图标转为关闭图标),增强交互反馈
- 点击子FAB后自动收起菜单,优化操作流程
内容的提问来源于stack exchange,提问作者Pantastix
相关产品推荐
相关产品推荐

