Long Press Draggable Flutter Example

In this article, we are going to integrate long press draggable widget in flutter application. You can check out flutter animations related articles.

Using LongPressDraggable widget, we can drag any child widget on long press event. In this flutter example, we are dragging text to other position. There are main two components in long press draggable widget: child & feedback. We can drag child widget on long press event. feedback widget is used to display when child widget is dragged.

LongPressDraggable widget has many properties. data property is used for data which will be dropped by draggable. childWhenDragging property is used to show rather than child when one drag is in progress. axis property is used to restrict long press draggable movement.

feedbackOffset is used to set target point to find drag target. dragAnchor property is used to decide position where child widget should be anchored during drag. We can also set limit how many items are dragged at a time by using maxSimultaneousDrags property. key property is used to control how one widget replaces another widget in tree.

onDragStarted callback is used to detect when child widget drag is started. onDragCompleted callback is used to detect when child widget is dragged to DragTarget widget. onDraggableCanceled callback is used to detect when draggable is dropped after drag is started.

 

Long Press Draggable Flutter

import ‘package:flutter/material.dart’;

class MyLongPressDraggableScreen extends StatefulWidget {
@override
_MyLongPressDraggableScreenState createState() => _MyLongPressDraggableScreenState();
}

class _MyLongPressDraggableScreenState extends State<MyLongPressDraggableScreen> {

Offset myOffset = Offset(75,250);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘Flutter Long Press Draggable Sample’),),
body: Center(
child: LayoutBuilder(
builder: (context, constraints) {
return Stack(
children: [
Positioned(
left: myOffset.dx,
top: myOffset.dy,
child: LongPressDraggable(
feedback: Text(‘CodingWithDhrumil’, style: TextStyle(color: Colors.deepOrangeAccent, fontSize: 30, fontWeight: FontWeight.bold)),
child: Text(‘CodingWithDhrumil’, style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
onDragEnd: (details) {
setState(() {
final adjustment = MediaQuery.of(context).size.height – constraints.maxHeight;
myOffset = Offset(details.offset.dx, details.offset.dy – adjustment);
});
},
),
),
],
);
},
),
),
);
}
}

 
 
 
long press draggable flutter
 
 

Leave a Reply