flutter 拖拽控件 Draggable DragTarget

拖拽控件 Draggable  DragTarget 使用

先直接贴出代码

import 'package:flutter/material.dart';


class DraggableDemo  extends StatefulWidget{
  @override
  _DraggableDemoState createState() {
    // TODO: implement createState
    return _DraggableDemoState();
  }

}


class  _DraggableDemoState  extends State<DraggableDemo>{
  Color _draggableColor = Colors.grey;
  Offset _offset=Offset(80, 80);
   Color yellowColor=Colors.yellowAccent;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Stack(
        children: <Widget>[
        Positioned(
        left: _offset.dx,
        top: _offset.dy,
         child:  Draggable(
          data:  yellowColor,
              child:Container(
            width: 100.0,
            height: 100.0,
            color:yellowColor,
          ),
          feedback: Container(
            width: 100.0,
            height: 100.0,
            color: yellowColor.withOpacity(0.5),
          ),
          onDraggableCanceled: (velocity,offset){
            print("---->onDraggableCanceled11");
            setState(() {
              this._offset=offset;
            });
          },
        )),

          Center(
            child: DragTarget(
              onWillAccept: (Color color){
                print("-----onWillAccept");
                return true;
              },
                onAccept: (Color color){
                  print("-----color");
                  setState(() {
                    _draggableColor=color;
                  });
                },
                builder: (context, candidateData, rejectedData){
                  print("-----builder");

                  return Container(
                  width: 200,
                  height: 200,
                  color: _draggableColor,
                );
               }
            ),

          )

        ],
      ),
    );
  }
}

注:上面代码中 Draggable 中的属性data传入的是  在类中声明的变量 Color yellowColor=Colors.yellowAccent,如果将data的变量直接写成data:Colors.yellowAccent,   那么DragTarget中的onAccept将不会接收到数据,DragTarget也就不会改变颜色,data必须传人一个变量。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值