I can't get x and y coordinate of movement in flutter container
I prefer just using DragUpdateDetails
that comes from onPanUpdate
.
body: GestureDetector(
onTap: () {},
onPanStart: (details) {
Offset position = details.localPosition;
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
});
},
onPanUpdate: (DragUpdateDetails details) {
Offset position = details.localPosition;
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
});
},
You must give the key to the container as a parameter
Container( key: key, ),
The key isn't attached to any widget:
Attach it like so:
Container(
key: key,
width: 500,
height: 500,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 2,
),
),
)
EDIT
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: GestureDetector(
onPanStart: (details) {
RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
Offset position = box.localToGlobal(Offset.zero);
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
});
},
onPanUpdate: (details) {
RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
Offset position = box.localToGlobal(Offset.zero);
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
});
},
child: Container(
width: 500,
height: 500,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 2,
),
),
),
),
);
}
This code above will always have the Container at Offset(0,0) that's why the values of X_Position
and Y_Position
is always 0.
To see changes, put the Container
in a Center
Like so:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: GestureDetector(
onPanStart: (details) {
RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
Offset position = box.localToGlobal(Offset.zero);
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
});
},
onPanUpdate: (details) {
RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
Offset position = box.localToGlobal(Offset.zero);
setState(() {
X_Position = position.dx;
Y_Position = position.dy;
});
},
child: Center(
child: Container(
width: 500,
height: 500,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 2,
),
),
),
),
),
);
}