2024年7月1日 01:07
How to Implement Draggable Widgets in Flutter?
Implementing draggable widgets in Flutter can be done using the Draggable and DragTarget widgets. Below, I'll walk you through how to use these widgets to create a basic drag-and-drop functionality.
- Using the
DraggableWidget: TheDraggablewidget enables users to drag it across the screen. You need to define the following properties:
data: The data passed toDragTargetduring dragging.child: The widget displayed when not being dragged.feedback: The widget that follows the finger during dragging.childWhenDragging: The widget left in its original position, which can be transparent or any placeholder.
Example code:
dartDraggable( data: 'Your dragged data', child: Container( width: 100.0, height: 100.0, color: Colors.blue, child: Center( child: Text('Drag me'), ), ), feedback: Container( width: 120.0, height: 120.0, color: Colors.lightBlue, child: Center( child: Text('Dragging'), ), ), childWhenDragging: Container( width: 100.0, height: 100.0, color: Colors.grey, child: Center( child: Text('Original Position'), ), ), );
- Using the
DragTargetWidget: TheDragTargetwidget allows receiving the dragged widget. It requires specifying callback functions to handle data acceptance or rejection:
onWillAccept: A function determining whether data is accepted.onAccept: The function invoked when data is accepted.builder: A function to build the displayed widget, which can change based on whether a widget is hovering.
Example code:
dartDragTarget( onWillAccept: (data) { return true; // Decide whether to accept the dragged widget based on data }, onAccept: (data) { // Handle the logic for accepting data print('Data received: $data'); }, builder: ( BuildContext context, List<dynamic> accepted, List<dynamic> rejected, ) { return Container( width: 200.0, height: 200.0, color: accepted.isEmpty ? Colors.red : Colors.green, child: Center( child: Text('Drop here!'), ), ); }, );
By combining Draggable and DragTarget, you can create complex drag-and-drop interactions in your Flutter app. This approach is not only suitable for simple data transfer but also for more complex interactions, such as sorting lists or moving cards.