Flutter
What is GestureDetector?
Learn to catch tap events with GestureDetector.
What is GestureDetector?
GestureDetector is a widget that listens to gestures such as tap, double tap and long press on its child. It has no visual effect of its own; it just wraps the widget you pass as child and captures the gestures performed on it. When a gesture happens, the callback you provided is called.
GestureDetector(
onTap: () {
print('Tapped');
},
child: Container(
width: 100,
height: 100,
color: Colors.blue,
),
)
The child parameter
GestureDetector listens to gestures performed on the widget passed as child. Without child there is no area to listen on, so child is almost always provided. The larger the child, the larger the touch area.
GestureDetector(
onTap: () => print('Tap'),
child: Text('Tap here'),
)
Exercise Write the onTap callback
Write a function named tapHandler. When called it should print Tapped. In main call this function and wire it as onTap of the GestureDetector.
Show example solution
import 'package:flutter/material.dart';
void dokunmaOlayi() {
print('Dokunuldu');
}
void main() {
dokunmaOlayi();
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: GestureDetector(
onTap: dokunmaOlayi,
child: Container(
width: 100,
height: 100,
color: Colors.blue,
),
),
),
),
);
}
}
Test yourself
-
Does GestureDetector itself produce a visual effect?
- Yes, it hides the child widget
- Yes, it draws a border around it
- No, it only listens to gestures
- Yes, it changes the background color
Show answer
No, it only listens to gestures — GestureDetector is invisible; it makes no visual change. It only wraps the child and listens to gestures.
-
Add the onTap parameter
GestureDetector(
child: Container(
width: 80,
height: 80,
color: Colors.red,
),
____: () => print('Merhaba'),
)
Show answer
GestureDetector(
child: Container(
width: 80,
height: 80,
color: Colors.red,
),
onTap: () => print('Merhaba'),
)
-
GestureDetector parts
- GestureDetector
- Listens to tap gestures
- onTap
- Single tap callback
- child
- The widget on which gestures are listened
- callback
- Function called when the event happens
Next lesson: onTap and onDoubleTap