I have strange behavior with a draggable item.
Each time I drag it on my stack, it goes down by around 80px (this is an approximation and maybe with another phone it could be something else) down from the drop position. The x value seems ok to me.
Here is the code:
class GesturePage extends StatefulWidget {
@override
_GesturePageState createState() => _GesturePageState();
}
class _GesturePageState extends State<GesturePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Gesture"),
),
body: Stack(
children: <Widget>[
DragBox(Offset(0.0, 80.0)),
],
),
);
}
}
class DragBox extends StatefulWidget {
final Offset initPosition;
DragBox(this.initPosition);
@override
DragBoxState createState() => DragBoxState();
}
class DragBoxState extends State<DragBox> {
Offset position = Offset(0.0, 0.0);
@override
void initState() {
super.initState();
position = widget.initPosition;
}
@override
Widget build(BuildContext context) {
return Positioned(
left: position.dx,
top: position.dy - 80.0,
child: Draggable(
data: widget.itemColor,
child: Container(
child: Image.asset('images/item.png'),
),
onDraggableCanceled: (velocity, offset) {
setState(() {
position = offset;
});
},
feedback: Container(
child: Image.asset('images/item.png'),
),
),
);
}
}
Anyone understand what is going on?
Also, is there a way to be able to see the x and y coordinates live when dragging the item?
Edit: Look for the 80.0 in the source code. This fixed my issue, but only for one emulator type. There is also another interesting code here
Yes, the thing is pretty simple. The 80 difference that you are having in y axis includes
24 px = For Status bar
56 px = For App bar / Navigation bar
Total = 80 px
And that's because you are receiving global position, you need to convert this to local position. Here is what you should do.
RenderBox referenceBox = context.findRenderObject();
Offset localPosition = referenceBox.globalToLocal(yourGlobalOffset);
Edit:
Make your Positioned as the children of Stack.
Replace your with mine
onDraggableCanceled: (velocity, offset) {
setState(() {
RenderBox renderBox = context.findRenderObject();
_position = renderBox.globalToLocal(offset);
});
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With