top of page

Gesture Detector in Flutter

Updated: Nov 27, 2022

It is a widget that detects gestures in Flutter. All the different types of gestures can be detected with the help of the GestureDetector Widget.

GestureDetector is used where we want the application to take some action when the user taps on the widget that is the child of this widget. We need to assign a child widget. On this widget, any gesture made will be detected.

The following gestures can be detected with the help of this widget.

  • Single Tap

  • Double Tap

  • Long Press

  • Drag

  • Pan

  • Force

  • Scale

All the gestures can be detected with this widget.



Syntax

The syntax for the GestureDetector widget is as follows. It primarily contains a child widget and a callback function which is one of the types above discussed. Here we have used a function to detect a single tap called onTap(){}.

GestureDetector(
  onTap: () {
    // triggered on tap
  },
  child: child_widget,
),

Example

In the following example, we have created a widget to detect and create a Snackbar to show which of the following widget is being tapped from the List of items.


import 'package:flutter/material.dart';

class GestureDetectorTutorial extends StatelessWidget {
  const GestureDetectorTutorial({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () => ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                "Item no. ${index + 1} tapped",
              ),
            ),
          ),
          child: Text(
            "Item no. ${index + 1}",
            style: const TextStyle(
              fontSize: 28.0,
              fontWeight: FontWeight.bold,
            ),
          ),
        );
      },
    );
  }
}


Output




Related Posts

See All

The image sharing apps, shopping apps, etc. have image zoom functionality required to see the image in detail. Today, we will learn to implement the same with the help of a widget, InteractiveViewer.

bottom of page