Created
November 26, 2019 21:32
-
-
Save mjohnsullivan/0dcb5997ec05cbfebaec73671e3a4db4 to your computer and use it in GitHub Desktop.
Handling draggable areas or elements drawn on a Flutter CustomPainter
This file contains 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(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Draggable Custom Painter', | |
home: Scaffold( | |
body: DraggableCustomPainter(), | |
), | |
); | |
} | |
} | |
class DraggableCustomPainter extends StatefulWidget { | |
@override | |
_DraggableCustomPainterState createState() => _DraggableCustomPainterState(); | |
} | |
class _DraggableCustomPainterState extends State<DraggableCustomPainter> { | |
var xPos = 0.0; | |
var yPos = 0.0; | |
final width = 100.0; | |
final height = 100.0; | |
bool _dragging = false; | |
/// Is the point (x, y) inside the rect? | |
bool _insideRect(double x, double y) => | |
x >= xPos && x <= xPos + width && y >= yPos && y <= yPos + height; | |
@override | |
Widget build(BuildContext context) { | |
return GestureDetector( | |
onPanStart: (details) => _dragging = _insideRect( | |
details.globalPosition.dx, | |
details.globalPosition.dy, | |
), | |
onPanEnd: (details) { | |
_dragging = false; | |
}, | |
onPanUpdate: (details) { | |
if (_dragging) { | |
setState(() { | |
xPos += details.delta.dx; | |
yPos += details.delta.dy; | |
}); | |
} | |
}, | |
child: Container( | |
child: CustomPaint( | |
painter: RectanglePainter(Rect.fromLTWH(xPos, yPos, width, height)), | |
child: Container(), | |
), | |
), | |
); | |
} | |
} | |
class RectanglePainter extends CustomPainter { | |
RectanglePainter(this.rect); | |
final Rect rect; | |
@override | |
void paint(Canvas canvas, Size size) { | |
canvas.drawRect(rect, Paint()); | |
} | |
@override | |
bool shouldRepaint(CustomPainter oldDelegate) => true; | |
} |
My only modification would be this! (Creating Paint() once)
https://gist.github.com/rodydavis/188c3425fd637dd5e20744b9874889bb
Great point! No need to endlessly recreate on every paint.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My only modification would be this! (Creating Paint() once)
https://gist.github.com/rodydavis/188c3425fd637dd5e20744b9874889bb