Open In App

Flutter – GestureDetector Widget

Last Updated : 16 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A GestureDetector is a very useful Flutter widget that allows you to recognize and respond to various touch gestures, such as taps, swipe, double taps, drags, and more. It provides a way to make your Flutter app interactive and responsive to user input. In this article, we are going to implement and deep dive into GestureDetector widget in Flutter. A sample video is given below to get an idea about what we are going to do in this article.

Basic Syntax of Gesture Detector

Dart




GestureDetector(
  onTap: () {
    // Handle the onTap gesture here
    print("Container tapped!");
  },
  child: Container(
    width: 200,
    height: 200,
    color: Colors.blue,
    child: Center(
      child: Text(
        "Tap Me!",
        style: TextStyle(fontSize: 24, color: Colors.white),
      ),
    ),
  ),
)


Required Tools

To build this app, you need the following items installed on your machine:

  • Visual Studio Code / Android Studio
  • Android Emulator / iOS Simulator / Physical Device device.
  • Flutter Installed
  • Flutter plugin for VS Code / Android Studio.

Step By Step Implementations

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(MyApp());
}


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      title: 'Swipe GestureDetector Example',
      home: SwipeGestureExample(),
    );
  }
}


Step 5: Create SwipeGestureExample Class

In this class we are going to Implement the GestureDetector whenever the user swipe the Container the color of the Container changes each time.Here we are going to apply GestureDetector’s onHorizontalDragUpdate to listen the swipes made by the user.Comments are added for better understanding.

GestureDetector(
onHorizontalDragUpdate:
_changeColorOnSwipe, // Call the function on horizontal drag
child: Container(
width: 200,
height: 200,
color: _backgroundColor, // Use the current background color
child: Center(
child: Text(
'Swipe me!',
style: TextStyle(
fontSize: 24,
color: Colors.white,
),
),
),
),
),

Dart




class SwipeGestureExample extends StatefulWidget {
  @override
  _SwipeGestureExampleState createState() => _SwipeGestureExampleState();
}
  
class _SwipeGestureExampleState extends State<SwipeGestureExample> {
  Color _backgroundColor = Colors.blue; // Initial background color
  
  void _changeColorOnSwipe(DragUpdateDetails details) {
    if (details.delta.dx > 0) {
      // Swipe right
      setState(() {
        _backgroundColor = Colors.green;
      });
    } else if (details.delta.dx < 0) {
      // Swipe left
      setState(() {
        _backgroundColor = Colors.red;
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Swipe GestureDetector Example'),
      ),
      body: Center(
        child: GestureDetector(
          onHorizontalDragUpdate:
              _changeColorOnSwipe, // Call the function on horizontal drag
          child: Container(
            width: 200,
            height: 200,
            color: _backgroundColor, // Use the current background color
            child: Center(
              child: Text(
                'Swipe me!',
                style: TextStyle(
                  fontSize: 24,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      title: 'Swipe GestureDetector Example',
      home: SwipeGestureExample(),
    );
  }
}
  
class SwipeGestureExample extends StatefulWidget {
  @override
  _SwipeGestureExampleState createState() => _SwipeGestureExampleState();
}
  
class _SwipeGestureExampleState extends State<SwipeGestureExample> {
  Color _backgroundColor = Colors.blue; // Initial background color
  
  void _changeColorOnSwipe(DragUpdateDetails details) {
    if (details.delta.dx > 0) {
      // Swipe right
      setState(() {
        _backgroundColor = Colors.green;
      });
    } else if (details.delta.dx < 0) {
      // Swipe left
      setState(() {
        _backgroundColor = Colors.red;
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Swipe GestureDetector Example'),
      ),
      body: Center(
        child: GestureDetector(
          onHorizontalDragUpdate:
              _changeColorOnSwipe, // Call the function on horizontal drag
          child: Container(
            width: 200,
            height: 200,
            color: _backgroundColor, // Use the current background color
            child: Center(
              child: Text(
                'Swipe me!',
                style: TextStyle(
                  fontSize: 24,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads