Flutter中Stack内GestureDetector点击无响应问题求助
解决BottomSheet中Positioned超出区域的GestureDetector点击无响应问题
问题出在你把关闭按钮通过Positioned(top: -40)放在了BottomSheet的布局边界之外,而BottomSheet默认只会处理自身范围内的手势事件,超出区域的点击会被忽略。
给你两种可行的解决方法:
方法一:调整BottomSheet的内边距,让按钮处于布局范围内
通过给BottomSheet的子组件添加顶部内边距,把按钮的位置纳入BottomSheet的可点击区域:
showBottomSheet( context: context, builder: (context) { return Padding( padding: const EdgeInsets.only(top: 40), // 留出按钮高度的内边距 child: Stack( clipBehavior: Clip.none, children: [ Container( height: 200, width: double.infinity, color: Colors.green, child: TextButton( onPressed: () => print('Hello'), child: const Text('A'), ), ), Positioned( top: -40, // 现在这个位置处于BottomSheet的内边距区域,属于可点击范围 left: MediaQuery.of(context).size.width / 2 - 50, child: GestureDetector( onTap: () { print('Bye'); Navigator.of(context).pop(); }, child: Container( height: 40, width: 100, decoration: BoxDecoration( color: Colors.red.shade50, borderRadius: const BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20), ), ), child: const Center( child: Text( 'Close', style: TextStyle(color: Colors.red), ), ), ), ), ), ], ), ); }, );
方法二:扩大BottomSheet的高度,将按钮包含在布局内
直接调整BottomSheet的总高度,把按钮的高度算进去,再调整绿色容器的位置:
showBottomSheet( context: context, builder: (context) { return Container( height: 240, // 绿色容器高度200 + 按钮高度40 child: Stack( clipBehavior: Clip.none, children: [ Positioned( top: 40, // 绿色容器下移,给按钮留出位置 child: Container( height: 200, width: 200, color: Colors.green, child: TextButton( onPressed: () => print('Hello'), child: const Text('A'), ), ), ), Positioned( top: 0, // 按钮放在BottomSheet顶部,处于布局范围内 child: GestureDetector( onTap: () { print('Bye'); Navigator.of(context).pop(); }, child: Container( height: 40, width: 100, decoration: BoxDecoration( color: Colors.red.shade50, borderRadius: const BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20), ), ), child: const Center( child: Text( 'Close', style: TextStyle(color: Colors.red), ), ), ), ), ), ], ), ); }, );
核心逻辑就是:确保点击按钮的区域属于BottomSheet的布局范围,这样手势事件才能被正常捕获和响应。
内容的提问来源于stack exchange,提问作者user22362195
相关产品推荐
相关产品推荐

