This article focuses on the Draggable and DragTarget of Flutter, a Widget that can be dragged on the screen.

Draggable

The constructor

Draggable(
  data: 4./// Control widgets can only be dragged horizontally
  //axis: Axis.horizontal,
	/// The widget that displays when stopped (default display)
  child:
	/// The widget displayed while dragging (the widget displayed at the dragged finger)
  feedback:
 	/// Display the widget in its original location while dragging
  childWhenDragging: 
),
Copy the code

Child Displays the widget by default;

Feedback drags when finger position is displayed in the widget

ChildWhenDraggingchild is dragged away to display the widget in its original position

Axis controls the direction of drag

axis: Axis.horizontal,

Callback

/// Start dragging
onDragStarted: () {
  print("----onDragStarted, start dragging");
},
/// drag to DragTarget and accept the callback
onDragCompleted: () {
  print("----onDragCompleted, drag completed");
},
/// Do not drag to DragTarget or drag incomplete callback
onDraggableCanceled: (v, offset) {
  print("----onDraggableCanceled, drag cancelled");
},
Copy the code

OnDragStarted Is the callback to start dragging

OnDragCompleted The callback that is dragged to Target and accepted

OnDraggableCancled didn’t drag to Target or callback when Target didn’t accept

DragTarget

The constructor

DragTarget(
  builder: (context, List<int> candidateData,
      List<dynamic> rejectedData) {
    //candidateData, the data when the Draggable is dragged to the DragTarget, is ready to accept
    print("----candidateData" + candidateData.toString());

    ///rejectData, when Draggable is added to DragTarget, is not accepted
    print("----rejectedData" + rejectedData.toString());

    /// The two data points are not yet on the top
    return Center(
      child: Text(candidateData.toString() +
          "--"+ rejectedData.toString()), ); },),Copy the code

The Widget constructor for Builder DragTarget that creates the Widget displayed by the DragTarget

Callback

 // receive Draggable data and determine whether to receive it
  onWillAccept: (data) {
    print("- onWillAccept, drag and drop" + data.toString() + "The target");
    if (data == 4) {
      return true;
    } else {
      return false; }},/// when the DragTarget is reached, let go
  onAccept: (data) {
    print("- onAccept, receives" + data.toString());
    scaffoldKey.currentState
        .showSnackBar(SnackBar(content: Text(data.toString())));
  },

  /// pull to the top, do not let go, and then leave
  onLeave: (data) {
    print("- onLeave, leave" + data.toString());
  },
Copy the code

OnWillAccept predicts whether the Draggable will be accepted

OnAccept accepts the Draggable callback

OnLeaveDraggable drags onto but does not release, leaving the callback directly

Making address:

Github.com/damengzai/f…

Wechat official account “Flutter Introduction”