Flutter's Draggable and DragTarget: The Drag-and-Drop Pair
Build drag-and-drop UI in Flutter with the Draggable and DragTarget widget pair. A Draggable carries data, and a DragTarget acts as a mailbox that accepts it. Use them for reordering lists. The footgun: drops fail silently if the data types don't match.
WHY IT EXISTS To provide a declarative, widget-based way to handle complex user gestures like dragging and dropping items across the screen. This abstracts away the low-level complexity of tracking pointer events, managing state, and rendering temporary visuals.
THE MENTAL MODEL A Draggable is a movable package. It has three visual states: its normal child view, the feedback view that follows your finger, and the optional childWhenDragging view left in its original spot. It also carries an invisible data payload. A DragTarget is a stationary mailbox. It inspects the data from an incoming Draggable and decides whether to accept the package.
HOW IT WORKS When a drag gesture begins on a Draggable, it displays its feedback widget on the screen's Overlay, following the pointer. The original spot can show the childWhenDragging widget or an empty space. As the feedback widget moves over a DragTarget, the target's builder function is called, allowing it to change appearance (e.g., highlight). When the user drops the widget, if it's over a compatible DragTarget, the target's onAccept callback fires with the data. If accepted, the Draggable's onDragCompleted is called; otherwise, onDraggableCanceled is called.
WHEN TO USE IT Use this pair for any feature requiring users to move an element. Common cases include: reordering items in a list, moving a file to a "delete" icon, dragging a product into a shopping cart, or organizing tasks on a kanban board.
WHEN NOT TO USE IT For simple taps or swipes, use GestureDetector. For complex, continuous gestures that don't involve a distinct "drop" action (like drawing on a canvas), you might use lower-level pointer event listeners. Draggable and DragTarget are specifically for the "pick up and drop" interaction model.
ONE CANONICAL EXAMPLE A simple app has several colored containers wrapped in Draggable widgets, each with its Color object as data. A central DragTarget widget displays a message. When a colored container is dragged and dropped onto the target, the onAccept callback receives the Color data and updates its own state to display that color, confirming the drop was successful.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.