Introduction
Here is how to implement drag and drop in a Flutter application and build awesome user interfaces for all input types. Give your users some gestures to play around!
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.
Want More Flutter Content?
Join my bi-weekly newsletter that delivers small Flutter portions right in your inbox. A title, an abstract, a link, and you decide if you want to dive in!
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:
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.