Det*_*per 3 dart flutter flutter-positioned flutter-state flutter-android
我只想在屏幕上拖动小部件,而不是拖放。
但是,每当我离开它并再次开始拖动时,它就会开始从开始的位置开始拖动。就好像它是一样reset。
我的猜测是 build 被一次又一次地调用,所以它会自动使用original position values. 我该如何解决?代码应该是什么?
换句话说,position就是设置为结束(100, 100)之后DragEvent。然后下一个拖动开始位置,(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,
),
),
),
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
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,
),
),
),
],
),
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2405 次 |
| 最近记录: |