SoFunction
Updated on 2025-03-01

Flutter framework implements Android drag to trash can delete

Draggable introduction

Draggable is a widget in the Flutter framework that enables users to drag a child component through gestures. It is a gesture-based way that allows the user to drag a specified part on the screen. Here are some detailed introductions about Draggable:

Constructor

Draggable constructor

Draggable<T>({
  Key? key,
  required ,
  ,
  ,
  ,
  ,
   = ,
   = ,
  ,
  ,
  ,
  ,
  ,
   = true,
  ,
   = DefaultDragAnchorStrategy,
})

Parameter description

  • child (Widget): The dragged child component.
  • feedback (Widget?): The feedback part displayed when dragging. If null, child is used as the feedback component.
  • data (T?): The data passed to DragTarget during dragging.
  • axis (Axis?): limits the axial direction of drag. Can be (horizontal) or (vertical).
  • childWhenDragging (Widget?): The part that replaces child when dragging. If null, child is displayed when dragging.
  • feedbackOffset (Offset): The offset of the feedback component relative to the drag gesture.
  • dragAnchor (DragAnchor): Controls the position of the drag anchor point. Can be (default, the anchor is in the center of the child component) or (the anchor is in the position of the drag gesture).
  • affinity (Axis?): Used to specify a case where aligned to an axis, can be or.
  • onDragStarted (VoidCallback?): Drag the callback function at the beginning.
  • onDragEnd (DraggableDetailsCallback?): The callback function at the end of dragging.
  • onDraggableCanceled (DraggableCanceledCallback?): The callback function when the drag is cancelled.
  • maxSimultaneousDrags (int?): The maximum number of drags simultaneously.
  • canDrag (bool): Whether to allow dragging. If false, Draggable will not respond to the drag gesture.
  • gestureRecognizer (DragGestureRecognizer?): A gesture recognizer for custom drag gesture detection.
  • dragAnchorStrategy (DragAnchorStrategy): A policy used to control drag anchor points.

Example of usage

Draggable&lt;int&gt;(
  data: 42,
  child: Container(
    width: 100,
    height: 100,
    color: ,
    child: Center(
      child: Text("Drag me"),
    ),
  ),
  feedback: Container(
    width: 120,
    height: 120,
    color: (0.5),
    child: Center(
      child: Text("Dragging..."),
    ),
  ),
  onDragStarted: () {
    // The action performed at the beginning of dragging    print("Drag started!");
  },
  onDragEnd: (details) {
    // The action performed when the drag is finished    print("Drag ended!");
  },
);

In this example, when the user drags a blue container containing the text "Drag me", the onDragStarted callback is fired, printing "Drag started!". At the end of the drag, the onDragEnd callback is fired, printing "Drag ended!". The dragged data is 42, which can be received and processed through DragTarget.

Introduction to DragTarget

DragTarget is a widget in the Flutter framework that receives drag operations and processes data passed during dragging. It is a way to work with Draggable, allowing you to specify how dragged objects should be received and processed.

Here is a detailed introduction to DragTarget:

Constructor

DragTarget<T>(
  {Key? key,
  required ,
  ,
  ,
  ,
   = ,
  ,
  ,
})

Parameter description

  • builder (Widget Function(BuildContext, List<T?>, List): is used to build a child component of DragTarget. builder accepts three parameters, namely BuildContext, the currently dragged data list, and the previously received data list.
  • onWillAccept (bool Function(T)?): Called when dragging an object into the DragTarget area, used to decide whether to accept the dragged object. If true is returned, onAccept will be called.
  • onAccept (void Function(T)?): Called when the drag object is released into the DragTarget area, used to process the accepted drag data.
  • onLeave (void Function(T)?): Called when dragging the object away from the DragTarget area.
  • hitTestBehavior (HitTestBehavior): Used to determine the behavior of click tests. The default value is , which means that clicking the test will be entrusted to the child component.
  • feedback (Widget?): A feedback component for customizing dragging.
  • child (Widget?): A child component used to place in the DragTarget area.

Example of usage

DragTarget&lt;int&gt;(
  builder: (BuildContext context, List&lt;int?&gt; candidateData, List&lt;dynamic&gt; rejectedData) {
    return Container(
      width: 200,
      height: 200,
      color: ,
      child: Center(
        child: Text("Drop here"),
      ),
    );
  },
  onWillAccept: (data) {
    // Called when dragging the object into the DragTarget area    // Return true to accept dragged object    return true;
  },
  onAccept: (data) {
    // Called when the drag object is released into the DragTarget area    // Process the accepted drag data    print("Accepted data: $data");
  },
  onLeave: (data) {
    // Called when dragging the object away from the DragTarget area  },
)

In this example, DragTarget is a gray container of size 200x200 with the "Drop here" text displayed. When a drag object enters this container, onWillAccept will be called to decide whether to accept the drag object. If true is returned, onAccept will be called when the drag object is released, processing the accepted drag data. onLeave is called when dragging the object away from the DragTarget area. This method can be used to implement drag-and-drop interactions, where DragTarget receives and processes Draggable's data.

How to receive data transmitted by DragTarget

DragTarget receives data passed from Draggable through the onAccept callback function. This callback function is called when the drag object is released into the DragTarget area.

Here is a simple example that demonstrates how to use Draggable and DragTarget to pass and receive data:

import 'package:flutter/';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Draggable and DragTarget Example'),
        ),
        body: MyDraggableAndDragTarget(),
      ),
    );
  }
}
class MyDraggableAndDragTarget extends StatefulWidget {
  @override
  _MyDraggableAndDragTargetState createState() =&gt; _MyDraggableAndDragTargetState();
}
class _MyDraggableAndDragTargetState extends State&lt;MyDraggableAndDragTarget&gt; {
  String data = 'Initial Data';
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: ,
      children: [
        Draggable&lt;String&gt;(
          data: 'Dragged Data',
          child: Container(
            width: 100,
            height: 100,
            color: ,
            child: Center(
              child: Text('Drag Me'),
            ),
          ),
          feedback: Container(
            width: 100,
            height: 100,
            color: (0.5),
            child: Center(
              child: Text('Dragging...'),
            ),
          ),
          childWhenDragging: Container(
            width: 100,
            height: 100,
            color: (0.5),
          ),
        ),
        SizedBox(height: 20),
        DragTarget&lt;String&gt;(
          builder: (BuildContext context, List&lt;String?&gt; candidateData, List&lt;dynamic&gt; rejectedData) {
            return Container(
              width: 150,
              height: 150,
              color: ,
              child: Center(
                child: Text('Drop Here'),
              ),
            );
          },
          onWillAccept: (data) {
            // Called when dragging the object into the DragTarget area            // Return true to accept dragged object            return true;
          },
          onAccept: (data) {
            // Called when the drag object is released into the DragTarget area            // Process the accepted drag data            setState(() {
               = data ?? 'No Data';
            });
          },
          onLeave: (data) {
            // Called when dragging the object leaves the DragTarget area          },
        ),
        SizedBox(height: 20),
        Text('Received Data: $data'),
      ],
    );
  }
}

In this example, Draggable contains a text box that you can drag. DragTarget is a gray container that when you drag a text box onto this container, it will receive the dragged data and display the received data on the screen.

Conclusion

Flutter is an open source UI toolkit developed by Google that allows you to create high-quality, beautiful applications on different platforms without writing a lot of platform-specific code. I will learn and delve into every aspect of Flutter. From basic knowledge to advanced skills, from UI design to performance optimization, Huanyin follows and discusses and learns together, and enters the wonderful world of Flutter together!

This is the article about the Flutter framework's implementation of Android drag to the trash can deletion effect. For more related content on Android Draggable and DragTarget, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!