dart - Draggable item always goes down by around 80px
问题描述
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 ofStack
.Replace your with mine
onDraggableCanceled: (velocity, offset) { setState(() { RenderBox renderBox = context.findRenderObject(); _position = renderBox.globalToLocal(offset); }); },
推荐阅读
- ios - 如何更改状态栏背景的颜色?
- javascript - 如何在将光标放在文本区域时弹出模式
- python - KeyError:运行 Ansible 剧本时的“用户”
- php - (Laravel) 每次数据库有变化就更新界面?
- mysql - 如果表只包含外键,它可以自动填充吗?
- jsf - 从阶段侦听器(beforePhase 或 afterPhase)访问 adf 中页面片段的 UI 组件
- sql - SQL Casting 无效数据类型
- sap - 在 Web Intelligence 中准确计算两个时间戳之间的营业时间
- javascript - Push 不是函数,Redux
- ios - iOS Material Components MDCButton在按下按钮时更改文本颜色