在探索Flutter的DragTarget类时,如果可以的话,我找不到任何机制可以挂接到“悬停事件”。这是一个示例:
class DropZone extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Container(
height: 40,
color: Colors.green,
child: DragTarget(
builder: (context, List<int> candidateData, rejectedData) {
print("dragged");
return new Container(color: Colors.red,);
},
onWillAccept: (data) {
return true;
},),
);
}
}
当可拖动对象悬停但尚未放置时,我想更改容器的颜色。在这种情况下,builder方法仅在初始渲染期间以及Draggable离开目标时执行。我怀疑我必须在onWillAccept方法中做一些事情,但不确定是什么。有人有解决方案吗?
答案 0 :(得分:2)
这是我想寻找的代码
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), Colors.green),
Positioned(
left: 100,
bottom: 0.0,
child: DragTarget(onAccept: (Color color) {
caughtColor = color;
}, builder: (
BuildContext context,
List<dynamic> accepted,
List<dynamic> rejected,
) {
return Container(
width: 200,
height: 200,
color: accepted.isEmpty ? caughtColor : Colors.grey.shade200,
);
}))
],
);
}
}
class DragBox extends StatefulWidget {
final Offset initPos;
final Color itemColor;
DragBox(this.initPos, 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: Container(
width: 100,
height: 100,
color: widget.itemColor,
),
onDraggableCanceled: (velocity, offset) {
setState(() {
position = offset;
});
},
feedback: Container(
width: 120,
height: 120,
color: widget.itemColor.withOpacity(0.5),
),
),
);
}
}