我正在制作一个以手势检测器为根的小部件,它的子项是一列,然后有多个不同的 subview ,其中一些是文本字段,但手势检测器仅在我按下文本字段时才触发,尽管 View 采用在 flutter 检查器中全屏显示这是我的构建方法
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
print("tap");
function(context);
},
child: Column(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: buildTopDivider(),
),
Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Column(
children: buildTextFields(),
),
),
),
Column(
children: buildIconContainer(),
),
],
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: buildBottomDivider(),
)
],
),
);
}
并附上一个屏幕截图,显示手势检测器占据了整个 View ,略有编辑但显示了问题,所以我希望能够按下此项目的任何位置并触发 onPress 方法,但目前如所述只有当我按下任何一个看起来很奇怪的文本 View 时才会触发,有什么想法吗?
最佳答案
使用此代码 GestureDetector.onTap
可以在红色区域的任何地方工作,除了 TextField
:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'foo text',
),
GestureDetector(
// behavior: HitTestBehavior.translucent,
onTap: () {
print("tap");
// function(context);
},
child: Column(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
// children: buildTopDivider(),
),
Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: Container(
color: Colors.red,
padding: const EdgeInsets.only(right: 8.0),
child: Column(
// children: buildTextFields(),
children: [
Text('foo bar baz'),
TextField(onTap: () => print('TextField tapped'),),
Text('foo bar baz'),
],
),
),
),
Column(
// children: buildIconContainer(),
),
],
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
// children: buildBottomDivider(),
)
],
),
)
],
),
),
);
}
}
您的代码会调用问题中未包含的函数,因此很难说出实际情况。
关于Flutter 手势检测器 onTap 仅在文本子项上触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54571404/