拖拽控件 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必须传人一个变量。