我想检测TabBarView上的手势,因此我将TabBarView包裹在GestureDetector小部件中,但是它不注册任何手势。滑动到不同的标签即可。我只想检测手势。
TabController _tabController;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(//I have 3 tabs in here at AppBar.bottum),
///This is where I need help with the GestureDetector not working.
body: GestureDetector(
onHorizontalDragStart: (DragStartDetails details) {
print('Start : ');
print(details);
},
child: TabBarView(controller: _tabController, children: <Widget>[
Tab(icon: Icon(Icons.category)),
Tab(icon: Icon(Icons.home)),
Tab(icon: Icon(Icons.star)),
]),
),
);
}
答案 0 :(得分:1)
嵌套手势小部件
出现此问题的原因是,这两个小部件都接受触摸输入,而当您有两个小部件都接受触摸输入时,长话短说,孩子赢得了这场战斗。这是长话。因此,您来自TabBarView
和GestureDetector
的所有输入都被发送到GestureArena
。那里的竞技场考虑了多个不同的因素,但故事的结尾是孩子总是赢。您可以通过使用自己的RawGestureDetector
定义自己的GestureFactory
来解决此问题,这将改变竞技场的表演方式。
RawGestureDetector(
gestures: {
AllowMultipleGestureRecognizer: GestureRecognizerFactoryWithHandlers<
AllowMultipleGestureRecognizer>(
() => AllowMultipleGestureRecognizer(),
(AllowMultipleGestureRecognizer instance) {
instance.onTap = () => print('Episode 4 is best! (parent container) ');
},
)
},
behavior: HitTestBehavior.opaque,
//Parent Container
child: Container(
color: Colors.blueAccent,
child: Center(
//Wraps the second container in RawGestureDetector
child: RawGestureDetector(
gestures: {
AllowMultipleGestureRecognizer:
GestureRecognizerFactoryWithHandlers<
AllowMultipleGestureRecognizer>(
() => AllowMultipleGestureRecognizer(), //constructor
(AllowMultipleGestureRecognizer instance) { //initializer
instance.onTap = () => print('Episode 8 is best! (nested container)');
},
)
},
//Creates the nested container within the first.
child: Container(
color: Colors.yellowAccent,
width: 300.0,
height: 400.0,
),
),
),
),
);
class AllowMultipleGestureRecognizer extends TapGestureRecognizer {
@override
void rejectGesture(int pointer) {
acceptGesture(pointer);
}
}
我要感谢Flutter Deep Dive: Gestures的作者纳什(Nash),这是一篇很棒的文章,我强烈建议您检查一下。
答案 1 :(得分:0)
GestureDetector
当您尝试使用 Stack
和 GestureDetector
时,会发生相同类型的问题。解决这个问题的简单方法是改变behavior
的{{1}}。
GestureDetector
我找到了这张表格 How to make a GestureDetector capture taps inside a Stack?。
请告诉我们这是否适合您。就我而言,对于 TabController _tabController;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(//I have 3 tabs in here at AppBar.bottum),
body: GestureDetector(
// Add This Line in Code.
behavior: HitTestBehavior.translucent,
onHorizontalDragStart: (DragStartDetails details) {
print('Start : ');
print(details);
},
child: TabBarView(controller: _tabController, children: <Widget>[
Tab(icon: Icon(Icons.category)),
Tab(icon: Icon(Icons.home)),
Tab(icon: Icon(Icons.star)),
],
),
),
);
}
和 Stack
我直接在两个小部件的子代上使用它,您可能需要将 TabBarView
的 behavior
更改为其他内容或使用它在 GestureDetector
的孩子身上。