Gesturedetector Flutter Example | Flutter Gestures in 2023

Gesturedetector flutter example are movements and actions performed physically on an app’s screen with the intention of commanding or controlling the app. The capability to communicate with users is crucial. The following are a few gesture examples:

  • Screen lock sliding.
  • Tap the screen of a mobile device.
  • Holding on to the button with your finger.

Introduction

A built-in mechanism for detecting gestures is not present in some widgets, such as the Container and Card widgets. These widgets are encased in the GestureDetector flutter example widget, which is solely used for gesture detection and does not produce any visual effects like a ripple.

The GestureDetector flutter widget functions by identifying gestures for which callbacks have been defined and reacting to the event. The callback receives a null value if the gesture is to be disabled.

The common gestures detected by the GestureDetector widget are listed below, along with the corresponding events and potential applications (all illustrations are credited to Luke Wroblewski’s Touch Gesture Reference Guide):

Scale

Gesturedetector flutter example- Scale
Scale
  1. onScaleUpdate — When the user is not in contact with the screen anymore, onScaleEnd is triggered. nd/or scale
  2. onScaleEnd — triggered once the user has lost contact with the screen Possible application for the scale gesture
  3. onScaleStart — triggered when the screen has made contact with the user, establishing a focal point and an initial scale of 1.0.

Scale gestures have the following uses:

  • Rotation
  • Vertical Drag
  • Zoom in/zoom out

Double Tap

Twice in a short period of time, the user tapped the screen in the same place.

Gesturedetector flutter example- Double Tap
Double Tap
  1. onDoubleTapDown — triggered when a user touches the screen, possibly with a double tap
  2. onDoubleTapCancel — triggered if the event that fired onDoubleTapDown is not a double tap.
  3. onDoubleTap — triggered whenever a user quickly and repeatedly taps the same spot on the screen twice.

People, who read this article also read: Flutter Liquid Swipe Animation

The following examples illustrate possible uses for the double-tap gesture:

  • Long press
  • Like/dislike
  • Resize an image
  • Screen on/off

Long Press

For a considerable amount of time, the user maintained contact with the screen at the same point.

Gesturedetector flutter example- Long Press
Long Press
  1. onLongPressCancel — When the event that fired onLongPressDown is not a long press, the trigger occurs.
  2. onLongPressStart — triggered when the beginning of a long press is discovered
  3. onLongPress — triggered after the detection of a long press
  4. onLongPressEnd — triggered when the conclusion of a long press is discovered
  5. onLongPressDown — triggered when a user touches the screen; this contact may be prolonged
  6. onLongPressMoveUpdate — triggered when a long press has been detected and the user has moved their finger.
  7. onLongPressUp — triggered when the end of a long press is discovered; contact has been released following the long press

The following are some potential uses for the long-press gesture:

  • The user pinched or spread the screen.
  • Move an icon
  • Scale
  • Show more options

Tap

A fingertip of the user made brief contact with the screen.

Gesturedetector flutter example- Tap
Tap
  1. onTapUp — triggered when the user removes their eyes from the screen
  2. onTapDown — triggered when the user makes physical contact with the screen, which could be a tap.
  3. onTapCancel — triggered if the event that fired on TapDown is not a tap
  4. onTap — triggered when a user only fleetingly touches the screen

The following are some potential uses for the tap gesture:

  • Cancel
  • Double-tap
  • Select
  • Submit

Vertical Drag

The user touched the screen and steadily moved their fingertip up and down.

Vertical Drag
Vertical Drag
  1. onVerticalDragStart — the user begins to move vertically after making contact with the screen, which triggers the action.
  2. onVerticalDragDown — it may move vertically when a user touches the screen and is triggered by that touch.
  3. onVerticalDragEnd — It starts when the conclusion of a vertical drag is found.
  4. onVerticalDragCancel — triggered if the event that caused VerticalDragDown to fire is not a vertical drag.
  5. onVerticalDragUpdate — triggered when a contact that has been moving vertically stops and starts again.

The vertical drag gesture may be used for the following purposes:

  • Scroll

Horizontal Drag

A steady horizontal movement was made by the user’s fingertip after making contact with the screen.

Horizontal Drag
Horizontal Drag
  1. onHorizontalDragStart — triggered as soon as the user starts moving horizontally after making contact with the screen.
  2. onHorizontalDragEnd — when a horizontal drag has ended and the end has been detected.
  3. onHorizontalDragCancel — occurs when an event that fired on HorizontalDragDown is not a horizontal drag.
  4. onHorizontalDragDown — when the user touches the screen, a movement may begin that could be horizontal.
  5. onHorizontalDragUpdate — triggered when a horizontally moving contact moves in a horizontal direction once more.

The following are some potential uses for the horizontal drag gesture:

  • Go to a different view by navigating.
  • Delete
  • Archive

This is not an exhaustive list of the gestures that were discovered. For a full list, refer to the official documentation.

Let’s give it a shot!

Starting Up

To use the GestureDetector flutter example widget:

  • Give a callback for the gesture you want to recognize.
  • This app needs to be updated.
  • Wrap the GestureDetector widget around the desired widget.

To demonstrate how the tap, double-tap, long press, and scale gestures work, we will create a straightforward demo app.

Make a fresh Flutter application

Clear the default code from your main.dart file before creating a new Flutter application.

UI update

These four files will be made by us. The folder hierarchy is displayed here.

main.dart

import 'package:flutter/material.dart';
import 'presentation/my_app_widget.dart';
void main() {
  runApp(const MyApp());
}

My_app_widget.dart

import 'package:flutter/material.dart';
import 'home_page.dart';
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Gesture Detector Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  const HomePage(),
    );
  }
}

Home_page.dart

import 'package:flutter/material.dart';
import 'widgets/widgets.dart';
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.symmetric(
            horizontal: width * 0.1, vertical: height * 0.2),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children:  const [
            MyCardWidget(),
            MyFavoriteIconWidget()
          ],
        ),
      ),
    );
  }
}

My_card_widget.dart

import 'dart:math';
import 'package:flutter/material.dart';
class MyCardWidget extends StatefulWidget {
  const MyCardWidget({
    Key? key,
  }) : super(key: key);
  @override
  State<MyCardWidget> createState() => _MyCardWidgetState();
}
class _MyCardWidgetState extends State<MyCardWidget> {
  @override
  Widget build(BuildContext context) {
    return const Card(
      child: SizedBox(
        height: 300,
        width: 300,
      ),
      color: Colors.yellow,
    );
  }
}

My_favorite_icon_widget.dart

import 'package:flutter/material.dart';
class MyFavoriteIconWidget extends StatefulWidget {
  const MyFavoriteIconWidget({
    Key? key,
  }) : super(key: key);

  @override
  State<MyFavoriteIconWidget> createState() => _MyFavoriteIconWidgetState();
}

class _MyFavoriteIconWidgetState extends State<MyFavoriteIconWidget> {
  @override
  Widget build(BuildContext context) {
    return const Icon(
     Icons.favorite_border,
      size: 40,
    );
  }
}

Your completed app should resemble this:

Output
Output

Let’s handle some gestures now that our user interface is prepared.

Managing the Tap Gesture

Now, in the my_favorite_icon_widget.dart file:

  1. Make the StatefulWidget’s selected flag property available.
  2. isSelected = false in the bool;
  3. Wrap the GestureDetector widget around the Icon widget.
  4. Don’t leave the onTap property’s callback as null.
  5. Depending on the value of the flag property value, alter the icon and icon color.
class _MyFavoriteIconWidgetState extends State<MyFavoriteIconWidget> {
  bool isSelected = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: (){
          setState(() {
            isSelected = !isSelected;
          });
        },
        child:  Icon(
          isSelected ? Icons.favorite: Icons.favorite_border,
          size: 40,
          color: isSelected? Colors.red: Colors.black ,
        ));
  }
}

Managing the Double-Tap Gesture

In the my_card_widget.dart file:

  1. Include a color property.
  2. GestureDetector should be wrapped around the Card widget.
  3. Give the onDoubleTap property a non-null callback.
  4. Based on the value of the color property, alter the color of the card.
class _MyCardWidgetState extends State<MyCardWidget> {
  Color bgColor = Colors.yellow;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onDoubleTap: (){
        setState(() {
          bgColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
        });
      },
      child:   Card(
        child: const SizedBox(
          height: 300,
          width: 300,
        ),
        color: bgColor,
      ),
    );
  }
}

Managing the Long Press Gesture

In the my_card_widget.dart file:

  1. Give the onLongPress property a non-null callback.
  2. Depending on the makeCircular property, alter the card’s shape.
  3. Add a makeCircular flag property
class _MyCardWidgetState extends State<MyCardWidget> {
  Color bgColor = Colors.yellow;
  bool makeCircular = false;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPress: (){
        setState(() {
          makeCircular = !makeCircular;
        });
      },
      child:   Card(
        shape: makeCircular? const CircleBorder(): const RoundedRectangleBorder(),
        child: const SizedBox(
          height: 300,
          width: 300,
        ),
        color: bgColor,
      ),
    );
  }
}

Managing the Scale Gesture

In the my_card_widget.dart file:

  1. Insert the _scaleFactor property.
  2. Include the _baseFactor property.
  3. Establish an initial scale by providing a non-null callback to the onScaleStart property.
  4. Establish a new scale by providing a non-null callback to the onScaleUpdate property.
  5. Return to the initial scale by providing a non-null callback to the onScaleEnd property.
  6. Transorm.scale widget should encircle the Card widget.
  7. Depending on the _scaleFactor’s value, modify the scale property.
class _MyCardWidgetState extends State<MyCardWidget> {
  Color bgColor = Colors.yellow;
  bool makeCircular = false;
  double _scaleFactor = 0.5;
  double _baseScaleFactor = 0.5;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onScaleStart: (details){
        _baseScaleFactor = _scaleFactor;
      },
      onScaleUpdate: (details){
        setState(() {
          _scaleFactor = _baseScaleFactor * details.scale;
        });
      },
      onScaleEnd: (details){
        // return to initial scale
        _scaleFactor = _baseScaleFactor;
      },
      child:   Transform.scale(
        scale: _scaleFactor,
        child: Card(
          shape: makeCircular? const CircleBorder(): const RoundedRectangleBorde(),
          child: const SizedBox(
            height: 300,
            width: 300,
          ),
        color: bgColor,
      ),
    );
  }
}

The following video demonstrates the gestures used:

Gesture Clarification

What transpires then when two delayed, fleeting touch events take place when we provide the onGestureDown event callback for tapping and double-taping?

Take this as an example:

Illustration
Illustration

Flutter determines which gesture the user intended when two or more gesture events with non-null callbacks are recognized by having each recognizer enter the gesture arena. The winning event in the gesture arena “battles” with the closing events, which are canceled. 

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

The following factors are considered by the gesture arena:

  • The amount of time a user touches a screen
  • How many pixels were moved in each direction
  • What movement is present in the room?
  • A move that signals success

The battle states are as follows:

  • Maybe — possibly the gesture
  • Hold — if it changes in a specific way; in our case, one tap happened, and if the second tap happens within the anticipated time, it might be a double tap. might be the gesture if it develops in a specific way.
  • Yes — announcement of victory
  • Cancel — removed from combat

Consider the following scenario, for instance:

  1. The triggers for onTapDown and onDoubleTapDown
  2. Both gestures are in competition with one another.
  3. The onTap callback is carried out after the tap gesture succeeds.
  4. OnDoubleTapCancel is triggered when the double-tap gesture fails and is canceled.

In this instance, the tap gesture prevailed because:

  1. There was a delay in time between the two taps.
  2. With a tap and a “yes,” victory was declared.
  3. After the double-tap was canceled and there was no other competitor, the tap gesture was the only one left.

Conclusion

We have examined the GestureDetector widget and discovered how it functions. We have mastered its use to incorporate interactivity into our application, and we have put some of the standard gestures—such as tap, long press, double-tap, and scale—into practice. Finally, we considered gesture classification.

Related articles

Flutter Navigation and Routing Example | Best Practices in 2023

We'll discuss the declarative approach for Flutter navigation and...

Flutter Widgets Examples | List of Widgets with Examples in 2023

We will discover flutter widgets examples, how to make...

Case Studies

eDental App

Case Study: eDental Dentist App

Our team recently embarked on an exciting project to develop the eDental Dentist App, a cutting-edge mobile application designed for both Android and iOS...

Voltage Lab SAAS App

Voltage Lab is an Electrical & Electronics Website and App that they wanted to launch a new SAAS app that would allow students to...
google play app store listing

Keyword Research for EEE & Cricket Live Score App

A Cricket Live Score App & Voltage Lab EEE Engineer App aimed to enhance their visibility on Google and the iOS app store, seeking...