Sub topic 12
Swipe to dismiss and drag and drop
This chapter covers two widgets that turn drags into higher-level actions. Dismissible removes an item when the user swipes it away. Draggable and DragTarget move data from one place to another. It assumes you know setState, ListView.builder, Stack, and the onPanUpdate callback from the earlier chapter on drag gestures.
Swipe to dismiss with Dismissible
Dismissible wraps one child and listens for a horizontal or vertical drag. The child slides away and the widget calls onDismissed. It uses the drag recognizers you already know, so it takes part in the gesture arena like any other drag handler.
Two rules cause most errors:
- Every
Dismissibleneeds a uniquekeythat identifies the data, not the position. onDismissedmust remove the item from your data source in the same frame. If the widget is still in the tree after the dismissal, Flutter throws an error saying a dismissedDismissibleis still part of the tree.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: InboxList())));
}
class InboxList extends StatefulWidget {
const InboxList({super.key});
@override
State<InboxList> createState() => _InboxListState();
}
class _InboxListState extends State<InboxList> {
final List<String> _items = List.generate(8, (i) => 'Message ${i + 1}');
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
final item = _items[index];
return Dismissible(
key: ValueKey(item),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 16),
child: const Icon(Icons.delete, color: Colors.white),
),
onDismissed: (direction) {
setState(() => _items.removeAt(index));
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$item deleted')));
},
child: ListTile(title: Text(item)),
);
},
);
}
}The ValueKey(item) ties the swipe state to the string, not to the row number. If you used the index as the key, removing row 2 would hand its half-finished animation state to the row that moves into position 2.
Directions and backgrounds
The direction parameter limits which way the item can move. The default is DismissDirection.horizontal.
| Value | Allowed swipe |
|---|---|
| `horizontal` | Left or right |
| `startToEnd` | Left to right in left-to-right text |
| `endToStart` | Right to left in left-to-right text |
| `vertical`, `up`, `down` | Vertical movement |
| `none` | No swipe, which disables the widget |
The background widget shows behind the child while it slides. If you also set secondaryBackground, then background shows for startToEnd swipes and secondaryBackground shows for endToStart swipes. Without a secondary background, background is used for both directions. The direction argument that onDismissed receives tells you which way the user swiped, so you can treat "archive" and "delete" differently.
Confirming before removal
confirmDismiss runs when the swipe passes the threshold. It returns a Future<bool?>. Returning true lets the dismissal finish. Returning false or null slides the item back.
Dismissible(
key: ValueKey(item),
confirmDismiss: (direction) {
return showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Delete this message?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('Delete'),
),
],
),
);
},
onDismissed: (direction) => setState(() => _items.remove(item)),
child: ListTile(title: Text(item)),
)Note the _items.remove(item) call here. It removes by value, so it stays correct even if the list changed while the dialog was open. A captured index can be stale after an await.
You can also change how far the user must drag with dismissThresholds, a map such as {DismissDirection.endToStart: 0.6}. The value is the fraction of the item's width. The default is 0.4. A fast fling dismisses the item even below the threshold.
Drag and drop with Draggable and DragTarget
Draggable and DragTarget work as a pair. A Draggable<T> carries a typed data value. A DragTarget<T> decides whether to accept that value when the user releases it over the target. The type parameter T matters: a target only considers draggables whose data is a T.
The Draggable parts
A Draggable shows three different widgets during its life:
childis what the user sees when nothing is happening.feedbackis the widget that follows the pointer. It is drawn in the overlay, outside your normal widget tree.childWhenDraggingreplaces the child in its original spot while the drag is active. If you omit it, the original child stays visible.
Because feedback lives in the overlay, it has no Material ancestor. Text inside it will render with a yellow double underline unless you wrap it in a Material.
The DragTarget parts
DragTarget<T> has these main callbacks:
onWillAcceptWithDetailsreturns abool. It runs as a draggable moves over the target. Returningfalserejects the data.onAcceptWithDetailsruns when the user releases an accepted draggable. The data is indetails.data.onLeaveruns when a draggable moves off the target without dropping.builderrebuilds the target. It receivescandidateData(accepted data currently hovering) andrejectedData(rejected data currently hovering). Use these lists to highlight the target.
A complete example
The app below has two fruit chips and a basket. The basket accepts fruit but rejects the rock, and it highlights while a valid item hovers.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: BasketDemo())));
}
class BasketDemo extends StatefulWidget {
const BasketDemo({super.key});
@override
State<BasketDemo> createState() => _BasketDemoState();
}
class _BasketDemoState extends State<BasketDemo> {
final List<String> _basket = [];
Widget _chip(String label, {double opacity = 1}) {
return Opacity(
opacity: opacity,
child: Chip(label: Text(label)),
);
}
Widget _source(String label) {
return Draggable<String>(
data: label,
feedback: Material(
color: Colors.transparent,
child: _chip(label),
),
childWhenDragging: _chip(label, opacity: 0.3),
child: _chip(label),
);
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [_source('apple'), _source('pear'), _source('rock')],
),
DragTarget<String>(
onWillAcceptWithDetails: (details) => details.data != 'rock',
onAcceptWithDetails: (details) {
setState(() => _basket.add(details.data));
},
builder: (context, candidateData, rejectedData) {
final hovering = candidateData.isNotEmpty;
return Container(
width: 240,
height: 120,
alignment: Alignment.center,
decoration: BoxDecoration(
color: hovering ? Colors.green.shade100 : Colors.grey.shade200,
border: Border.all(
color: rejectedData.isNotEmpty ? Colors.red : Colors.black45,
),
),
child: Text(
_basket.isEmpty ? 'Drop fruit here' : _basket.join(', '),
),
);
},
),
],
);
}
}Variations you will need
LongPressDraggablestarts the drag only after a long press. Use it inside scrollable lists. A plainDraggablecompetes with the list's scroll drag in the gesture arena, and the scroll often wins or makes the drag feel unreliable.axis: Axis.horizontalrestricts movement to one axis.dragAnchorStrategycontrols where the feedback sits relative to the pointer.maxSimultaneousDragslimits concurrent drags of one widget. Setting it to 0 disables dragging.
Testing both interactions
WidgetTester.drag performs a drag from the center of a finder's widget by an offset. For a Dismissible, drag past the threshold and let the animation finish with pumpAndSettle.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('swiping a row removes it', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: InboxList())),
);
expect(find.text('Message 1'), findsOneWidget);
await tester.drag(find.text('Message 1'), const Offset(-500, 0));
await tester.pumpAndSettle();
expect(find.text('Message 1'), findsNothing);
});
}The test assumes InboxList is imported from your app. For drag and drop, use tester.drag from the draggable to the target, or tester.timedDrag for finer control, then pump and check the target's text.
Common mistakes
- Using the list index as the
Dismissiblekey. - Forgetting to remove the item in
onDismissed. - Omitting
Materialaroundfeedback. - Declaring
DragTargetwithout a type, so it acceptsdynamicdata it cannot use safely. - Placing a
Dismissibleinside a widget that scrolls in the same direction, which causes both to fight for the gesture.
Exercise
A list shows tasks, and swiping a row to the right should archive it while swiping left should delete it. Which two Dismissible properties let you show a different colored background for each direction, and how does onDismissed tell which action to run?
Show answer
Set background for the startToEnd swipe (right in left-to-right text) and secondaryBackground for the endToStart swipe (left). In onDismissed, check the DismissDirection argument: archive the task when it is startToEnd, delete it when it is endToStart. In both cases remove the task from the data source with setState, and give each row a key based on the task's id.
Exercise
Your Draggable feedback text shows a yellow double underline while dragging. Why does this happen and how do you fix it?
Show answer
The feedback widget is drawn in the overlay, which has no Material ancestor to supply a default text style. Wrap the feedback widget in a Material, for example Material(color: Colors.transparent, child: ...).