一个拖拽的目标区域,可接收Draggable组件的信息。可以获取拖拽时的回调。

相关组件

Draggable LongPressDraggable

DragTarget基本操作

【builder】:组件构造器【DragTargetBuilder
【onWillAccept】:拖入时【Function(T)】
【onAccept】:拖入成功【Function(T)】
【onLeave】:拖入再拖出【Function(T)】
106.gif

  1. import 'package:flutter/material.dart';
  2. class CustomDragTarget extends StatefulWidget {
  3. @override
  4. _CustomDragTargetState createState() => _CustomDragTargetState();
  5. }
  6. class _CustomDragTargetState extends State<CustomDragTarget> {
  7. Color _color = Colors.grey;
  8. String _info = 'DragTarget';
  9. @override
  10. Widget build(BuildContext context) {
  11. return Container(
  12. child: Column(
  13. children: <Widget>[
  14. Wrap(
  15. children: _buildColors(),
  16. spacing: 10,
  17. ),
  18. SizedBox(height: 20,),
  19. _buildDragTarget()
  20. ],
  21. ),
  22. );
  23. }
  24. List<Widget> _buildColors() {
  25. var colors = [
  26. Colors.red,
  27. Colors.yellow,
  28. Colors.blue,
  29. Colors.green,
  30. Colors.orange,
  31. Colors.purple,
  32. Colors.cyanAccent
  33. ];
  34. return colors
  35. .map(
  36. (e) => Draggable<Color>(
  37. child: Container(
  38. width: 30,
  39. height: 30,
  40. alignment: Alignment.center,
  41. child: Text(
  42. colors.indexOf(e).toString(),
  43. style: TextStyle(
  44. color: Colors.white, fontWeight: FontWeight.bold),
  45. ),
  46. decoration: BoxDecoration(color: e, shape: BoxShape.circle),
  47. ),
  48. data: e,
  49. feedback: Container(
  50. width: 25,
  51. height: 25,
  52. decoration: BoxDecoration(color: e, shape: BoxShape.circle),
  53. )),
  54. )
  55. .toList();
  56. }
  57. Widget _buildDragTarget() {
  58. return DragTarget<Color>(
  59. onLeave: (data) => setState(() => _info='onLeave'),
  60. onAccept: (data) => setState(() {
  61. _info='onAccept';
  62. _color = data;
  63. }),
  64. onWillAccept: (data) {
  65. setState(() {
  66. _info='onWillAccept';
  67. });
  68. print("onWillAccept: data = $data ");
  69. return data != null;
  70. },
  71. builder: (context, candidateData, rejectedData) => Container(
  72. width: 150.0,
  73. height: 50.0,
  74. color: _color,
  75. child: Center(
  76. child: Text(
  77. _info,
  78. style: TextStyle(color: Colors.white),
  79. ),
  80. )));
  81. }
  82. }