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

相关组件

Draggable DragTarget

LongPressDraggable与DragTarget联用

  1. <br />【child】 : 孩子 【Widget】<br />【feedback】 : 拖拽时的孩子 【Widget】<br />【axis】 : 拖动的轴 【Axis】<br />【data】 : 数据 【T】<br />【onDragStarted】 : 开始拖拽 【Function()】<br />【onDragEnd】 : 结束拖拽 【Function(DraggableDetails)】<br />【onDragCompleted】 : 拖拽完成 【Function()】<br />【onDraggableCanceled】 : 拖拽取消 【Function(Velocity,Offset)】<br />![107.gif](https://cdn.nlark.com/yuque/0/2020/gif/326147/1589449157028-fb8ca727-50f7-4c3e-887b-e9476a7647c8.gif#align=left&display=inline&height=146&margin=%5Bobject%20Object%5D&name=107.gif&originHeight=146&originWidth=403&size=94228&status=done&style=none&width=403)
  1. import 'package:flutter/material.dart';
  2. class CustomLongPressDraggable extends StatefulWidget {
  3. @override
  4. _CustomLongPressDraggableState createState() => _CustomLongPressDraggableState();
  5. }
  6. class _CustomLongPressDraggableState extends State<CustomLongPressDraggable> {
  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) => LongPressDraggable<Color>(
  37. onDragStarted: () => setState(() => _info = '开始拖拽'),
  38. onDragEnd: (d) => setState(() => _info = '结束拖拽'),
  39. onDragCompleted: () => _info = '拖拽完成',
  40. onDraggableCanceled: (v, o) => _info = '拖拽取消',
  41. child: Container(
  42. width: 30,
  43. height: 30,
  44. alignment: Alignment.center,
  45. child: Text(
  46. colors.indexOf(e).toString(),
  47. style: TextStyle(
  48. color: Colors.white, fontWeight: FontWeight.bold),
  49. ),
  50. decoration: BoxDecoration(color: e, shape: BoxShape.circle),
  51. ),
  52. data: e,
  53. feedback: Container(
  54. width: 25,
  55. height: 25,
  56. decoration: BoxDecoration(color: e, shape: BoxShape.circle),
  57. )),
  58. )
  59. .toList();
  60. }
  61. Widget _buildDragTarget() {
  62. return DragTarget<Color>(
  63. onAccept: (data) => setState(() {
  64. _info='onAccept';
  65. _color = data;
  66. }),
  67. builder: (context, candidateData, rejectedData) => Container(
  68. width: 150.0,
  69. height: 50.0,
  70. color: _color,
  71. child: Center(
  72. child: Text(
  73. _info,
  74. style: TextStyle(color: Colors.white),
  75. ),
  76. )));
  77. }
  78. }