Open In App

Flutter – LongPressDraggable Widget

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

In Flutter, LongPressDraggable is a widget that allows you to create draggable UI elements that respond to long-press gestures. In this article, we are going to implement the LongPressDraggable widget and explore some properties of it. A sample video is given below to get an idea about what we are going to do in this article.

Some Properties of LongPressDraggable

child:
Type: Widget
Description: The child widget that you want to make draggable. This is the widget that will respond to the long-press gesture and can be dragged around the screen.
feedback:
Type: Widget
Description: The widget that appears as feedback when the draggable widget is being dragged. Typically, this is a semi-transparent version of the child widget that provides visual feedback to the user during the drag operation.
data:
Type: T
Description: An optional data value of generic type T that can be associated with the draggable widget. This data can be used to carry additional information or state when the widget is dragged.
axis:
Type: Axis
Description: Specifies the axis along which the widget can be dragged. You can choose between Axis.horizontal (default) and Axis.vertical.
childWhenDragging:
Type: Widget
Description: An optional replacement widget that is displayed in place of the child while it is being dragged. This allows you to change the appearance of the widget during dragging.
onDragStarted:
Type: VoidCallback
Description: A callback function that is invoked when the drag operation starts (i.e., when the long-press gesture is detected).
onDragEnd:
Type: DraggableCanceledCallback
Description: A callback function that is invoked when the drag operation ends (i.e., when the user releases the draggable widget). It provides information about the position where the widget was released and whether it was accepted or canceled.
feedbackOffset:
Type: Offset
Description: An optional offset that determines the position of the feedback widget relative to the pointer during dragging. You can use this to adjust the visual offset of the feedback widget.
ignoringFeedbackSemantics:
Type: bool
Description: If true, the semantics of the feedback widget are ignored during dragging. This is useful when the feedback widget should not be considered as part of the widget tree for accessibility purposes.
maxSimultaneousDrags:
Type: int
Description: The maximum number of simultaneous drags allowed. By default, it's set to 1, which means only one draggable widget can be dragged at a time. You can increase this value if you want to allow multiple simultaneous drags.

Basic Syntax of LongPressDraggable

LongPressDraggable<T>(
child: YourChildWidget(),
feedback: YourFeedbackWidget(),
data: YourDataObject,
axis: Axis.vertical, // or Axis.horizontal
childWhenDragging: YourChildWhenDraggingWidget(),
onDragStarted: () {
// Callback when the drag operation starts
},
onDragEnd: (details) {
// Callback when the drag operation ends
// `details` provides information about the drag, e.g., position and whether it was accepted or canceled
},
)

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 Implementation

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: 'LongPressDraggable Example',
      home: DraggableExample(),
    );
  }
}


Step 5: Create DraggableExample Class

In this class we are going to Implement the LongPressDraggable widget whenever the user Long press the Container then the user can able to drag the container accross the screen.Comments are added for better understanding.

 LongPressDraggable(
child: Container(
width: 100,
height: 100,
color: Colors.blue,
child: Center(
child: Text(
'Drag me!',
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
),
),
feedback: Container(
width: 100,
height: 100,
color: Colors.blue.withOpacity(0.5),
child: Center(
child: Text(
'Dragging...',
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
),
),
onDragStarted: () {
// Callback when the drag operation starts
setState(() {
_isDragged = true; // Update the drag state
});
},
onDragEnd: (details) {
// Callback when the drag operation ends
setState(() {
_isDragged = false; // Update the drag state
});
},
),

Dart




class DraggableExample extends StatefulWidget {
  @override
  _DraggableExampleState createState() => _DraggableExampleState();
}
  
class _DraggableExampleState extends State<DraggableExample> {
  bool _isDragged = false; // Variable to track whether the widget is being dragged
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('LongPressDraggable Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            LongPressDraggable(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
                child: Center(
                  child: Text(
                    'Drag me!',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              feedback: Container(
                width: 100,
                height: 100,
                color: Colors.blue.withOpacity(0.5),
                child: Center(
                  child: Text(
                    'Dragging...',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              onDragStarted: () {
                // Callback when the drag operation starts
                setState(() {
                  _isDragged = true; // Update the drag state
                });
              },
              onDragEnd: (details) {
                // Callback when the drag operation ends
                setState(() {
                  _isDragged = false; // Update the drag state
                });
              },
            ),
            SizedBox(height: 20),
            _isDragged
                ? Text('Widget is being dragged!')
                : Text('Widget is not being dragged.'),
          ],
        ),
      ),
    );
  }
}


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: 'LongPressDraggable Example',
      home: DraggableExample(),
    );
  }
}
  
class DraggableExample extends StatefulWidget {
  @override
  _DraggableExampleState createState() => _DraggableExampleState();
}
  
class _DraggableExampleState extends State<DraggableExample> {
  bool _isDragged = false; // Variable to track whether the widget is being dragged
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('LongPressDraggable Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            LongPressDraggable(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
                child: Center(
                  child: Text(
                    'Drag me!',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              feedback: Container(
                width: 100,
                height: 100,
                color: Colors.blue.withOpacity(0.5),
                child: Center(
                  child: Text(
                    'Dragging...',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              onDragStarted: () {
                // Callback when the drag operation starts
                setState(() {
                  _isDragged = true; // Update the drag state
                });
              },
              onDragEnd: (details) {
                // Callback when the drag operation ends
                setState(() {
                  _isDragged = false; // Update the drag state
                });
              },
            ),
            SizedBox(height: 20),
            _isDragged
                ? Text('Widget is being dragged!')
                : Text('Widget is not being dragged.'),
          ],
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads