gpt4 book ai didi

flutter : Drag Widgets across screen (Not Drag and Drop)

转载 作者:行者123 更新时间:2023-12-01 23:20:41 26 4
gpt4 key购买 nike

我只想在屏幕上拖动小部件,而不是拖放。

但是,每当我离开它并再次开始拖动时,它就会从开始的位置开始被拖动。就好像它被重置了

我的猜测是构建被一次又一次地调用,所以它自动使用原始位置值。我该如何解决?代码应该是什么?

所以换句话说,在 DragEvent 结束后,position 被设置为 (100, 100)。然后下一次拖动从 (100, 100) 开始,而不是小部件被拖放到的最后一个位置。

我也用 GlobalPosition 尝试过这个,但得到了相同的结果。这是我的代码:

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

double x1 = 100.0;
double x2 = 200.0;
double y1 = 100.0;
double y2 = 200.0;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Drag widget on screen'),
),
body: Stack(
children: [
Positioned(
left: x1,
top: y1,
child: GestureDetector(
onHorizontalDragUpdate: (details) {
setState(() {
x1 = details.localPosition.dx;
y1 = details.localPosition.dy;
});
},
child: Container(
width: 64,
height: 64,
color: Colors.amber,
),
),
),
Positioned(
left: x2,
top: y2,
child: GestureDetector(
onHorizontalDragUpdate: (details) {
setState(() {
x2 = details.localPosition.dx;
y2 = details.localPosition.dy;
});
},
child: Container(
width: 64,
height: 64,
color: Colors.red,
),
),
),
],
),
);
}
}

Drag Widgets across screen

最佳答案

  double x1 = 100.0, x2 = 200.0, y1 = 100.0,
y2 = 200.0, x1Prev = 100.0, x2Prev = 200.0, y1Prev = 100.0,
y2Prev = 100.0;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Drag widget on screen'),
),
body: Stack(
children: [
Positioned(
left: x1,
top: y1,
child: GestureDetector(
onPanDown:(d){
x1Prev = x1;
y1Prev = y1;
},
onPanUpdate: (details) {
setState(() {
x1 = x1Prev + details.localPosition.dx;
y1 = y1Prev + details.localPosition.dy;
});
},
child: Container(
width: 64,
height: 64,
color: Colors.amber,
),
),
),
Positioned(
left: x2,
top: y2,
child: GestureDetector(
onPanDown:(d){
x2Prev = x2;
y2Prev = y2;
},
onPanUpdate: (details) {
setState(() {
x2 = x2Prev + details.localPosition.dx;
y2 = y2Prev + details.localPosition.dy;
});
},
child: Container(
width: 64,
height: 64,
color: Colors.red,
),
),
),
],
),
);
}

关于 flutter : Drag Widgets across screen (Not Drag and Drop),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68140651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com