How to Implement Drag and Drop in a Flutter Application

Flutter category image

Here is how to implement drag and drop in a Flutter application and build awesome user interfaces for all input types.

Drag and drop is a common UX pattern on mobile, tablets, and desktops. It’s easy and convenient, regardless of the input type (finger, stylus, mouse) you use. Here’s how to implement drag and drop in a Flutter application.

Draggable

We start with the Draggable widget. This is the widget the users can drag in your Flutter app. You need to provide a child and a feedback widget.

The child widget is always displayed while the feedback widget is displayed during a drag operation and it follows the pointer.

With the data property you can assign any data object to the Draggable widget. This will be relevant during the drop operation.

You can wrap anything in a Draggable widget to offer drag and drop functionality in no time.

Here is a code example of a Draggable with a Text widget when dragged:

?

Hint

Be aware that your feedback widget has no style information. You need to pass it or wrap it in a Material widget.

Join my free Medium Newsletter!

Get an overview of my new Medium content with my monthly newsletter. Save time and pick what you like to read!

DragTarget

A DragTarget widget uses a builder function to determine its visual representation. The candidates argument contains the Draggable widgets and their assigned data objects.

candidates is empty by default. But as soon as a Draggable enters the DragTarget widget, it contains the assigned data objects of the Draggable. You can display two different UI states: when the user hasn’t dragged anything onto a target and when he is about to drop it.

The onAccept function triggers when the user drops a Draggable over a DragTarget. The passed data argument contains the corresponding data object of the Draggable if any.

Here is the code for a DragTarget that reacts on Draggables when they are dropped:

And here is a short demo video of how it can look eventually:

Demo video of how to implement drag and drop in a Flutter application by author
Demo video of how to implement drag and drop in a Flutter application by author

Conclusion

In this article, you learned how to implement drag and drop in a Flutter application and build awesome user interfaces. It’s an easy solution but can be a big gain in terms of usability.

Related articles