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.
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.
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:
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.
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:
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.