我正在练习可拖动的小部件。感谢Tensor Programming的精彩视频。我能够理解事情的运作方式。
但是,我不确定一件事。假设如果DragBox
之一被点击,我想在DragBox
里面获取文本。我用Container
包装了GestureDetector
,但是我不知道如何使onTap
函数通过widget.label
传递到AppState
。
我应该使用构造函数或其他方法传递它吗? 有人知道实现这一目标很热吗? 预先感谢。
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: App(),
),
);
}
}
class App extends StatefulWidget {
@override
AppState createState() => AppState();
}
class AppState extends State<App> {
Color caughtColor = Colors.grey;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
DragBox(Offset(0.0, 0.0), 'Box One', Colors.blueAccent),
DragBox(Offset(200.0, 0.0), 'Box Two', Colors.orange),
DragBox(Offset(300.0, 0.0), 'Box Three', Colors.lightGreen),
Positioned(
left: 100.0,
bottom: 0.0,
child: DragTarget(
onAccept: (Color color) {
caughtColor = color;
},
builder: (
BuildContext context,
List<dynamic> accepted,
List<dynamic> rejected,
) {
return Container(
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: accepted.isEmpty ? caughtColor : Colors.grey.shade200,
),
child: Center(
child: Text("Drag Here!"),
),
);
},
),
)
],
);
}
}
class DragBox extends StatefulWidget {
final Offset initPos;
final String label;
final Color itemColor;
DragBox(this.initPos, this.label, this.itemColor);
@override
DragBoxState createState() => DragBoxState();
}
class DragBoxState extends State<DragBox> {
Offset position = Offset(0.0, 0.0);
@override
void initState() {
super.initState();
position = widget.initPos;
}
@override
Widget build(BuildContext context) {
return Positioned(
left: position.dx,
top: position.dy,
child: Draggable(
data: widget.itemColor,
child: GestureDetector(
onTap() {
// want to pass widget.label here
},
child: Container(
width: 100.0,
height: 100.0,
color: widget.itemColor,
child: Center(
child: Text(
widget.label,
style: TextStyle(
color: Colors.white,
decoration: TextDecoration.none,
fontSize: 20.0,
),
),
),
),
),
onDraggableCanceled: (velocity, offset) {
setState(() {
position = offset;
});
},
feedback: Container(
width: 120.0,
height: 120.0,
color: widget.itemColor.withOpacity(0.5),
child: Center(
child: Text(
widget.label,
style: TextStyle(
color: Colors.white,
decoration: TextDecoration.none,
fontSize: 18.0,
),
),
),
),
));
}
}
答案 0 :(得分:1)
能否请您参考this答案。在链接
RootPage
与App
类似,AppState
与_RootPageState
类似,DragBox
与FeedPage
和DragBoxState
与_feedPageState
如果没有帮助,请发表评论,我可以为您的App