Here we are going to explore the Draggable widget in Flutter.
Introduction
A widget that can be dragged from to a drag target widget.
Check out the official: Draggable Class
When a draggable widget recognizes the start of a drag gesture, it displays a feedback widget that tracks the user’s finger across the screen. If the user lifts their finger while on top of a DragTarget, that target is given the opportunity to accept the data carried by the draggable.
The ignoringFeedbackPointer defaults to true, which means that the feedback widget ignores the pointer during hit testing. Similarly, ignoringFeedbackSemantics defaults to true, and the feedback also ignores semantics when building the semantics tree.
On multitouch devices, multiple drags can occur simultaneously because there can be multiple pointers in contact with the device at once. To limit the number of simultaneous drags, use the maxSimultaneousDrags property. The default is to allow an unlimited number of simultaneous drags.
This widget displays child when zero drags are under way. If childWhenDragging is non-null, this widget instead displays childWhenDragging when one or more drags are underway. Otherwise, this widget always displays child.
Implementation
Create a DraggableWidget class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
class DraggableWidget extends StatefulWidget { const DraggableWidget(); @override State<DraggableWidget> createState() => _DraggableWidgetState(); } class _DraggableWidgetState extends State<DraggableWidget> { int acceptedData = 0; @override Widget build(BuildContext context) { return Center( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Draggable<int>( // Data is the value this Draggable stores. data: 10, feedback: Container( color: Colors.deepOrange, height: 100, width: 100, child: const Icon(Icons.directions_run), ), childWhenDragging: Container( height: 100.0, width: 100.0, color: Colors.pinkAccent, child: const Center( child: Text('Child When Dragging'), ), ), child: Container( height: 100.0, width: 100.0, color: Colors.lightGreenAccent, child: const Center( child: Text('Draggable'), ), ), ), DragTarget<int>( builder: ( BuildContext context, List<dynamic> accepted, List<dynamic> rejected, ) { return Container( height: 100.0, width: 100.0, color: Colors.cyan, child: Center( child: Text('Value is updated to: $acceptedData'), ), ); }, onAccept: (int data) { setState(() { acceptedData += data; }); }, ), ], ), ); } } |
Flutter Draggable Demo App:
Thanks for reading.
Happy Coding 🙂
For more Flutter tutorials visit Mobikul Blogs.