DragTarget

While a Draggable allows a widget to be dragged, a DragTarget provides a destination for the draggable.

For example, in chess, a chess piece is a draggable whereas a square box on the chessboard is a drag target.

Here, the knight is accepted by the DragTarget .

The code for this example goes:

bool accepted = false; DragTarget(builder: (context, List<String> candidateData, rejectedData) {

return accepted ? WhiteKnight(size: 90.0,) : Container();

}, onWillAccept: (data) {

return true;

}, onAccept: (data) {

accepted = true;

},),

NB: The DragTarget is surrounded by a black colored container which is not shown in the code for brevity.

Let’s look at the parameters of the DragTarget in more detail.

Note: The “data” in the following sections refers to the data parameter of the Draggable .

Builder

The builder builds the actual widget inside the DragTarget . This function is called every time a Draggable is hovered over the DragTarget or is dropped onto it.

This function has three parameters, context, candidateData and rejectedData.

candidateData is the data of a Draggable whilst it is hovering over the DragTarget , ready for acceptance by DragTarget .

rejectedData is the data of a Draggable hovering over a DragTarget at moment it is not accepted.

Note that both of these are dealing with Draggables which are hovering over the DragTarget . At this point, they are not dropped onto it yet.

Now, how does the DragTarget know what to accept?

onWillAccept

onWillAccept is a function which gives us the Draggable data for us to decide whether to accept or reject it.

This is where the data we attached onto the Draggable becomes important. We use the data passed to accept or reject specific Draggables .

For example if our Draggable is:

Draggable(

data: "Knight",

// ...

),

then we can do:

DragTarget(

// ...

onWillAccept: (data) {

if(data == "Knight") {

return true;

} else {

return false;

}

},

),

This will only accept the Draggable if the data is “Knight”.

This function is called when the Draggable is first hovered over the DragTarget .

onAccept

If the Draggable is dropped onto the DragTarget and onWillAccept returns true, then onAccept is called.

onAccept also gives us the data of the Draggable and is usually used for storing the Draggable dropped over DragTarget .

onLeave