我有以下代码:
import 'package:flutter/material.dart';
class PScreen extends StatefulWidget {
@override
_PScreenState createState() => _PScreenState();
}
class _PScreenState extends State<PScreen> {
double width = 70.0, height = 70.0;
double _x = 0;
double _y = 0;
AppBar appBar;
Widget circle() {
return Container(
width: width,
height: height,
child: Center(
child: Text(
"Drag",
style: Theme.of(context).textTheme.headline,
),
),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
);
}
Widget draggable() {
return Positioned(
left: _x,
top: _y,
child: Draggable(
child: circle(),
feedback: circle(),
childWhenDragging: Container(),
onDragEnd: (dragDetails) {
setState(
() {
_x = dragDetails.offset.dx;
// We need to remove offsets like app/status bar from Y
_y = dragDetails.offset.dy -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top;
},
);
},
),
);
}
@override
Widget build(BuildContext context) {
appBar = AppBar(
title: Text('Drag'),
leading: BackButton(onPressed: () {
Navigator.pop(context, false);
}),
);
return Scaffold(
appBar: appBar,
body: Stack(
children: <Widget>[
draggable(),
circle(),
],
),
);
}
}
使用这段代码,我可以在屏幕上拖动一个圆圈,当我放置它时,圆圈停留在我离开的位置,这就是我想要做的。我的问题是我需要在屏幕上绘制其他内容,例如绘制另一个圆圈。当我将其他元素放入堆栈中时,我无法再拖动可拖动圆圈。如果删除堆栈内的“circle()”,代码将起作用,但对于堆栈内的其他元素,代码将不起作用。
我该怎么做?谢谢你。
您将第二个圆圈放在第一个圆圈的顶部,这就是它不起作用的原因。相反,用位置小部件包裹它并正确对齐第二个圆圈,以便您可以毫无问题地与第一个圆圈交互。
Positioned(
left:0.0,
bottom:0.0,
child: circle()),
所以,你的完整代码将如下所示
class PScreen extends StatefulWidget {
@override
_PScreenState createState() => _PScreenState();
}
class _PScreenState extends State<PScreen> {
double width = 70.0, height = 70.0;
double _x = 0;
double _y = 0;
AppBar appBar;
Widget circle() {
return Container(
width: width,
height: height,
child: Center(
child: Text(
"Drag",
style: Theme.of(context).textTheme.headline,
),
),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
);
}
Widget draggable() {
return Positioned(
left: _x,
top: _y,
child: Draggable(
child: circle(),
feedback: circle(),
childWhenDragging: Container(),
onDragEnd: (dragDetails) {
setState(
() {
_x = dragDetails.offset.dx;
// We need to remove offsets like app/status bar from Y
_y = dragDetails.offset.dy -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top;
},
);
},
),
);
}
@override
Widget build(BuildContext context) {
appBar = AppBar(
title: Text('Drag'),
leading: BackButton(onPressed: () {
Navigator.pop(context, false);
}),
);
return Scaffold(
appBar: appBar,
body: Stack(
children: <Widget>[
draggable(),
Positioned(
left:0.0,
bottom:0.0,
child: circle()),
],
),
);
}
}
我创建了解决这个问题的包轻松拖放