GestureDetector in Flutter

18-Sep-2024

Learn how to use GestureDetector to detect and respond to various user interactions

The GestureDetector widget is used to detect and respond to various gestures such as tapping, dragging, and scaling.
A versatile widget that can wrap other widgets and provide them with gesture-related functionality.

There Are Some Common Attributes for GestureDetector

onTap
Single Click Tapped
onDoubleTap
Double Tapped
onLongPress
Long Pressed
onVerticalDragUpdate
Vertical Drag Update

Here's a simple example of using a GestureDetector in Flutter:

File open lib->main.dart file −



import 'package:flutter/material.dart';

void main() {
runApp(
MyApp()
);
}
class MyApp extends StatefulWidget{

@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text('GestureDetector Example',
style:TextStyle(fontSize: 20,color: Colors.white)),
),
body: Center(
child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [

GestureDetector(
onTap: () {
print('Tapped');
},
onDoubleTap: () {
print('Double Tapped');
},
onLongPress: () {
print('Long Pressed');
},
onVerticalDragUpdate: (DragUpdateDetails details) {
print('Vertical Drag Update: ${details.primaryDelta}');
},
child: Container(
width: 300.0,
height: 100.0,
color: Colors.blue,
child: Center(
child: Text('Press me',
style: TextStyle(color: Colors.white,fontSize: 20),
),
),
)
)
],
),
)

));

}


}








Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.


Output:


Comments