I am trying to detect a tap on the screen. I've tried multiple variation of using the GestureDetector
but that just leads to the app detecting tap on the child element and not the screen.
Here is the code:
class QQHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.blueGrey,
),
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('QuoteQuota'),
),
body: GestureDetector(
onTap: () => print('Tapped'),
child: QQBody(),
),
),
);
}
}
class QQBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'Hello, World!'
),
);
}
}
Output: "tapped" printed when I click "Hello, World!".
Expected Output: "tapped" printed when I click anywhere on the screen with Text in the Center.
How do I do this?
Use GestureDetector's behavior property and pass HitTestBehavior. opaque to it, which recognizes entire screen and detects the tap when you tap anywhere on the screen.
Another option is to use debouncing to prevent this kind of behaviour ie with easy_debounce, or implementing your own debounce. Show activity on this post. And when you disable the component, it starts ignoring the touches within the boundary of the widget.
Use GestureDetector's
behavior
property and pass HitTestBehavior.opaque
to it, which recognizes entire screen and detects the tap when you tap anywhere on the screen.
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => print('Tapped'),
child: QQBody(),
),
Hope this answers your question.
Like Darshan said, you can trigger Tap by wrapping the body inside a Gesture detector like this...
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => print('Tapped'),
child: QQBody(),
),
Also in some cases, you may need to avoid trigger clicking on other widgets while tapping anywhere in body. That can be solved by using IgnorePointer
Widget
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
print('This will click');
},
// -------- No Widget below tree will be trigger click.
child: IgnorePointer(
ignoring: ClassLibrary.selected != null ? true : false,
child: TabBarView(
children: [
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With