Im trying to Drag a container with GestureDetector
, but when i dragg to the edges of the screen the container is going off the screen.
I wanted it to stop when it reaches the edges of the screen.
Here is the example code
import 'package:flutter/material.dart';
class DrawDraggableRectangle extends StatefulWidget {
const DrawDraggableRectangle({super.key});
@override
State<DrawDraggableRectangle> createState() => _DrawDraggableRectangleState();
}
class _DrawDraggableRectangleState extends State<DrawDraggableRectangle> {
double zoneHeight = 122;
double zoneWidth = 112;
double topY = 21;
double leftX = 16;
late double initX;
late double initY;
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
top: topY,
left: leftX,
child: GestureDetector(
onPanStart: (DragStartDetails details) {
setState(() {
initX = details.globalPosition.dx;
initY = details.globalPosition.dy;
});
},
onPanUpdate: (DragUpdateDetails details) {
final dx = details.globalPosition.dx - initX;
final dy = details.globalPosition.dy - initY;
initX = details.globalPosition.dx;
initY = details.globalPosition.dy;
setState(() {
topY = topY + dy;
leftX = leftX + dx;
});
},
child: Container(
height: zoneHeight,
width: zoneWidth,
//color: Colors.red.withOpacity(0.5),
decoration: BoxDecoration(
color: Colors.transparent,
border: Border.all(
color: Colors.pink, // Set border color
width:
3.0), // Set border width// Make rounded corner of border
),
),
),
),
],
);
}
}