Last active
October 19, 2022 15:22
-
-
Save rohan20/1461e9b4b297ed3cb125f54aa638c633 to your computer and use it in GitHub Desktop.
Flutter Panable/Moveable/Draggable Widget
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DartPad:
https://dartpad.dev/1461e9b4b297ed3cb125f54aa638c633?
Demo GIF: