Flutter Draggable And DragTarget 拖拽控件

 

Draggable 拖拽控件

DragTarget 接收Draggable的控件

效果图

 Flutter Draggable And DragTarget 拖拽控件

代码实现

添加Column组件

Column中添加 DragTarget和Draggable组件

Column(
  children: <Widget>[
    SizedBox(height: 20,),
    DragTarget(
      onWillAccept:(String data){
        //接收所有
        return true;
      },
      builder: (context, candidateData, rejectedData){
        String srt = candidateData != null && candidateData.length > 0 ? candidateData[0] : _text;
        return Container(
          alignment: Alignment.center,
          height: 250,
          width: 250,
          color: Colors.black26,
          child: Text(srt),
        );
      },
      
      onAccept:(String data){
        //接收到数据
        print('onAccept : $data');
        setState(() {
          _text = data;
        });
      },
      onLeave:(String data){
        //数据来了 又离开了
        print('onLeave : $data');
      },
    ),
    SizedBox(height: 20,),

    Draggable(
      data: '我是Draggable数据',
      // affinity:Axis.vertical,
      feedbackOffset: Offset.fromDirection(1.0),
      child: Container(
        alignment: Alignment.center,
        height: 150,
        width: 150,
        color: Colors.blue,
        child: Text('我是Draggable数据'),
      ),
      feedback: Material(
        child: Container(
          alignment: Alignment.center,
          height: 150,
          width: 150,
          color: Colors.blue,
          child: Text('我是Draggable数据'),
        ),
      ),
      onDragStarted:(){
        setState(() {
          _text = '初始数据';
        });
      },
      onDraggableCanceled:(Velocity velocity, Offset offset){
        print('$velocity -- $offset');
      },
    )
  ],
),

扩展

DragTarget 随机背景颜色,选中对应颜色Draggable拖动到DragTarget,

拖拽正确DragTarget 随机背景颜色,拖拽错误DragTarget会左右颤动提示。

Flutter Draggable And DragTarget 拖拽控件

以上Demo使用了ColumnTrembleDragTargetGridViewDraggable等组件完成。

 

完整代码

查看完整代码

上一篇:实现页面元素的拖拽(jqueryui实现)


下一篇:10 分钟上手 Vue 组件 Vue-Draggable