class DragTargetWidget extends StatefulWidget {
@override
_DragTargetWidgetState createState() => _DragTargetWidgetState();
}
class _DragTargetWidgetState extends State<DragTargetWidget> {
Color caughtColor = Colors.red;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Scaffold(
appBar: AppBar(
title: const Text('DragTarget Widgets Demo'),
centerTitle: true,
backgroundColor: Colors.red,
),
body: Stack(
children: <Widget>[
DragBox(
const Offset(0.0, 0.0),
'Drag This',
Colors.pink,
),
DragBox(
const Offset(250.0, 0.0),
'Drag This',
Colors.grey,
),
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: 150.0,
height: 150.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28.0),
color: accepted.isEmpty
? caughtColor
: Colors.grey.shade200,
),
child: const Center(
child: Text("You can 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 = const 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: 120.0,
height: 120.0,
color: widget.itemColor,
child: Center(
child: Text(
widget.label,
style: const TextStyle(
color: Colors.white,
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: const TextStyle(
color: Colors.white,
decoration: TextDecoration.none,
fontSize: 18.0,
),
),
),
),
),
);
}
}
Be the first to comment.