Gesture Detector
in Flutter is used to detect the user’s gestures on the application. It is a non-visual widget.
We can place another widget inside the Gesture Detector
and as a result the Gesture Detector
will capture all these events (gestures) and execute the tasks accordingly. It notifies when the particular motion event occurs.
Let’s create a new application and learn more about Gesture Detector
. We will use the following command to create a new flutter application:
flutter create gesture_detector_flutter
We can run the application by using the following command:
flutter run
Now in the main.dart
file, we will add a Gesture Detector
. The Gesture Detector
will have the following features:
1- Tap:
When the widget inside the Gesture Detector
is tapped once, the function or the code inside the onTap()
function will run.
2- Double Tap:
When the widget inside the Gesture Detector
is tapped twice, the function or the code inside the onDoubleTap()
function will run.
3- Long Press:
When the widget inside the Gesture Detector
is pressed for a long time, the function or the code inside the onLongPress()
function will run.
Note: Some other features of the
Gesture Detector
enable us to get the current location of the gesture on the screen using theonHorizontalDragUpdate
oronVerticalDragUpdate
functions. We can also get the user’s gesture/swipe velocity with thedragEndDetails
.
Now, we will make a simple gesture detection application that will contain a simple Container
widget with all the above working functions. We will write the following code snippet in main.dart
:
class _MyHomePageState extends State<MyHomePage> {bool _lightIsOn = false;@overrideWidget build(BuildContext context) {return Scaffold(body: Container(child: Column(children: <Widget>[Padding(child: Icon(Icons.lightbulb_outline,color: _lightIsOn ? Colors.yellow.shade600 : Colors.black,size: 60,),),GestureDetector(onTap: () {setState(() {_lightIsOn = !_lightIsOn;final snackBar = SnackBar(content: Text('Tap Function'));ScaffoldMessenger.of(context).showSnackBar(snackBar);});},onDoubleTap: (){setState(() {_lightIsOn = !_lightIsOn;final snackBar = SnackBar(content: Text('Double Tap Function'));ScaffoldMessenger.of(context).showSnackBar(snackBar);});},onLongPress: (){setState(() {_lightIsOn = !_lightIsOn;final snackBar = SnackBar(content: Text('Long Press Function'));ScaffoldMessenger.of(context).showSnackBar(snackBar);});},child: Text(_lightIsOn ? 'TURN LIGHT OFF' : 'TURN LIGHT ON'),),),],),),);}}
You can also download the complete application and code from this git repo: