GestureDetector lets your app notice when you touch or swipe the screen. It helps make your app interactive.
0
0
GestureDetector in Flutter
Introduction
You want to detect taps on a button or image.
You want to respond when the user swipes left or right.
You want to detect long presses to show extra options.
You want to track dragging movements on the screen.
You want to make any widget respond to touch gestures.
Syntax
Flutter
GestureDetector(
onTap: () {
// code to run when tapped
},
child: Widget(),
)The child is the widget that listens for gestures.
You can use many gesture callbacks like onTap, onLongPress, onPanUpdate, etc.
Examples
This detects a tap on a blue square and prints a message.
Flutter
GestureDetector(
onTap: () {
print('Tapped!');
},
child: Container(color: Colors.blue, width: 100, height: 100),
)This detects a long press on the text.
Flutter
GestureDetector(
onLongPress: () {
print('Long pressed!');
},
child: Text('Hold me'),
)This detects dragging movements on the icon.
Flutter
GestureDetector(
onPanUpdate: (details) {
print('Dragged by ${details.delta}');
},
child: Icon(Icons.drag_handle),
)Sample App
This app shows a teal box with the text "Tap me". When you tap the box, a message appears at the bottom saying "You tapped the box!".
Flutter
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('GestureDetector Example')), body: Center( child: GestureDetector( onTap: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('You tapped the box!')), ); }, child: Container( width: 150, height: 150, color: Colors.teal, alignment: Alignment.center, child: const Text( 'Tap me', style: TextStyle(color: Colors.white, fontSize: 24), ), ), ), ), ), ); } }
OutputSuccess
Important Notes
GestureDetector does not show any visual change by itself. You can add visual feedback inside the gesture callbacks.
Make sure the child widget has a size; otherwise, gestures might not be detected.
Use HitTestBehavior if you want to control how gestures pass through overlapping widgets.
Summary
GestureDetector listens for touch gestures on its child widget.
Use it to detect taps, long presses, drags, and more.
It helps make your app interactive and responsive to user touches.