Skip to content

Instantly share code, notes, and snippets.

@rohan20
Last active October 19, 2022 15:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohan20/1461e9b4b297ed3cb125f54aa638c633 to your computer and use it in GitHub Desktop.
Save rohan20/1461e9b4b297ed3cb125f54aa638c633 to your computer and use it in GitHub Desktop.
Flutter Panable/Moveable/Draggable Widget
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Stack(
children: [
PanableWidget(),
],
),
),
);
}
/// A pan-able/move-able/draggable widget that doesn't pan/move/drag beyond the dimensions of the screen.
class PanableWidget extends StatefulWidget {
@override
_PanableWidgetState createState() => _PanableWidgetState();
}
class _PanableWidgetState extends State<PanableWidget> {
double containerHeight = 100;
double containerWidth = 100;
double xPosition = 0;
double yPosition = 0;
Color color;
@override
void initState() {
super.initState();
color = Colors.blue;
}
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
double screenHeight = MediaQuery.of(context).size.height;
return Positioned(
top: yPosition,
left: xPosition,
child: GestureDetector(
onPanUpdate: (tapInfo) {
setState(() {
xPosition = _isXCoordinateMoreThanScreenWidth(tapInfo, screenWidth)
? screenWidth - containerWidth // stick to right edge of the screen
: _isXCoordinateLessThanZero(tapInfo)
? 0 // stick to left edge of the screen
: xPosition + tapInfo.delta.dx;
yPosition = _isYCoordinateMoreThanScreenHeight(tapInfo, screenHeight)
? screenHeight - containerHeight // stick to bottom edge of the screen
: _isYCoordinateLessThanZero(tapInfo)
? 0 // stick to top edge of the screen
: yPosition + tapInfo.delta.dy;
});
},
child: Container(width: containerWidth, height: containerHeight, color: color),
),
);
}
bool _isXCoordinateMoreThanScreenWidth(DragUpdateDetails tapInfo, double screenWidth) {
return xPosition + containerWidth + tapInfo.delta.dx > screenWidth;
}
bool _isXCoordinateLessThanZero(DragUpdateDetails tapInfo) => xPosition + tapInfo.delta.dx <= 0;
bool _isYCoordinateMoreThanScreenHeight(DragUpdateDetails tapInfo, double screenHeight) {
return yPosition + containerHeight + tapInfo.delta.dy > screenHeight;
}
bool _isYCoordinateLessThanZero(DragUpdateDetails tapInfo) => yPosition + tapInfo.delta.dy <= 0;
}
@rohan20
Copy link
Author

rohan20 commented Dec 26, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment