【发布时间】:2019-10-17 04:58:07
【问题描述】:
我正在尝试实现以下逻辑:
- 用户点击区域;
- 在指定坐标处生成一个新的小部件;
- 用户可以将新小部件拖动到新位置。
第 1 步和第 2 步效果很好,但是在第 3 步中,用户可以拖动小部件,但不会改变他的位置
这就是它现在的工作方式: https://media.giphy.com/media/h4Hhm5vchkcJi3IFqH/giphy.gif
代码:
class WidgetPaint extends StatefulWidget {
WidgetPaint({this.imagefromcam});
File imagefromcam;
@override
_WidgetPaintState createState() => _WidgetPaintState();
}
class _WidgetPaintState extends State<WidgetPaint> {
GlobalKey _globalKey2 = new GlobalKey();
Offset locationPoints;
var commentWidgets = List<Widget>();
var btn;
@override
void initState() {
super.initState();
locationPoints = Offset(100.0, 100.0);
}
@override
Widget build(BuildContext context) {
return Container(
width: 800.0,
height: 500.0,
child: RepaintBoundary(
key: _globalKey2,
child: Stack(
children: <Widget>[
GestureDetector(
onTapUp: (TapUpDetails detail) {
setState(() {
RenderBox _object = context.findRenderObject();
locationPoints =
_object.globalToLocal(detail.globalPosition);
print("locpoints: $locationPoints");
addButton();
});
},
] +
commentWidgets)),
);
}
Widget dragButton() {
return RawMaterialButton(
onPressed: () {},
child: new Icon(
Icons.pause,
color: Colors.blue,
size: 15.0,
),
shape: new CircleBorder(),
fillColor: Colors.white,
);
}
void addButton() {
btn = new Positioned(
left: locationPoints.dx,
top: locationPoints.dy,
child: Draggable(
child: dragButton(),
feedback: dragButton(),
onDraggableCanceled: (Velocity velocity, Offset offset) {
setState(() {
print("Location points: $locationPoints");
locationPoints = offset;
});
},
));
setState(() {
commentWidgets.add(btn);
});
}
如何改变可拖动小部件的位置?
更新 如果我删除 GestureDetector 并将可拖动的小部件直接放入堆栈,一切正常,但在这种情况下,我无法动态添加新的小部件
Widget build(BuildContext context) {
return Container(
width: 800.0,
height: 500.0,
child: RepaintBoundary(
key: _globalKey2,
child: Stack(
children: <Widget>[
Positioned(
left: 100.0,
height: 50.0,
child: Text(locationPoints.dx.toString()),
),
Positioned(
left: 100.0,
top: 20.0,
child: Text(locationPoints.dy.toString()),
),
Positioned(
left: locationPoints.dx,
top: locationPoints.dy,
child: Draggable(
child: dragButton(),
feedback: dragButton(),
onDraggableCanceled:
(Velocity velocity, Offset offset) {
setState(() {
print("Location points: $locationPoints");
RenderBox _object = context.findRenderObject();
locationPoints = _object.globalToLocal(offset);
});
},
)),]
【问题讨论】:
-
我在您的代码中看不到
DragTarget。也许我错了,但我认为这是缺少的 -
如果我理解正确,
DragTarget是可选的。我可以使用方法onDraggableCanceled: (Velocity velocity, Offset offset) { setState(() { print("Location points: $locationPoints"); locationPoints = offset; });获取当前位置 -
正如我所说,也许我错了。我只是将它与
DragTarget一起使用。您是否尝试使用另一个回调?onDragEnd或onDragCompleted -
同样的结果。但是,如果我从 Stack 中删除
GestureDetector,它就可以正常工作(下面的评论)