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
),
),
),
),
],
);
}
}

You can try to
clamp()the values assigned to y and x to the boundaries of your screen. In the example below I useddouble.infinityfor the upper value as we don't know exact size of the screen at this time.See this in practice using DartPad
If you'd like to make sure that the
Positionedstays within arbitrary bounds you may try to use LayoutBuilder aroundStackto get the constraints. Then you would be able to clamp the right and bottom edge in a similar way.