我正在使用扑动
我有一个使用此代码的圆形 container
new Container( width: 50.0, height: 50.0, decoration: new BoxDecoration( shape: BoxShape.circle)
我想让这个圆圈像这样在屏幕上移动
我怎样才能做到这一点 . 谢谢
您正在寻找的是Draggable小部件 . 然后,您可以使用传递的 onDraggableCanceled 处理转换,并使用偏移量来更新放置
onDraggableCanceled
onDraggableCanceled :(velocity,offset){ //update the position here }
Update
检查图像后,你需要"Drop me here" part为DragTarget,它有一个方法 onAccept ,当你拖放 Draggable 时它将处理逻辑
onAccept
Draggable
您可以使用 Draggable 类拖动要拖动的项目,并将其放置或粘贴到屏幕上的某个位置,您必须使用 DragTarget 类包装该项目 . 在 DragTarget 类 onAccept 方法中,您可以在其中编写逻辑 . 你也可以在这里引用我的代码
DragTarget
import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.indigo, ), home: new MyHomePage(title: 'Flutter Demo Drag Box'), ); } } class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(title), ), body: new DragGame(), // This trailing comma makes auto-formatting nicer for build methods. ); } } class DragGame extends StatefulWidget { @override _DragGameState createState() => new _DragGameState(); } class _DragGameState extends State<DragGame> { int boxNumberIsDragged; @override void initState() { boxNumberIsDragged = null; super.initState(); } @override Widget build(BuildContext context) { return new Container( constraints: BoxConstraints.expand(), color: Colors.grey, child: new Stack( children: <Widget>[ buildDraggableBox(1, Colors.red, new Offset(30.0, 100.0)), buildDraggableBox(2, Colors.yellow, new Offset(30.0, 200.0)), buildDraggableBox(3, Colors.green, new Offset(30.0, 300.0)), ], )); } Widget buildDraggableBox(int boxNumber, Color color, Offset offset) { return new Draggable( maxSimultaneousDrags: boxNumberIsDragged == null || boxNumber == boxNumberIsDragged ? 1 : 0, child: _buildBox(color, offset), feedback: _buildBox(color, offset), childWhenDragging: _buildBox(color, offset, onlyBorder: true), onDragStarted: () { setState((){ boxNumberIsDragged = boxNumber; }); }, onDragCompleted: () { setState((){ boxNumberIsDragged = null; }); }, onDraggableCanceled: (_,__) { setState((){ boxNumberIsDragged = null; }); }, ); } Widget _buildBox(Color color, Offset offset, {bool onlyBorder: false}) { return new Container( height: 50.0, width: 50.0, margin: EdgeInsets.only(left: offset.dx, top: offset.dy), decoration: BoxDecoration( color: !onlyBorder ? color : Colors.grey, border: Border.all(color: color)), ); } }
2 回答
您正在寻找的是Draggable小部件 . 然后,您可以使用传递的
onDraggableCanceled
处理转换,并使用偏移量来更新放置Update
检查图像后,你需要"Drop me here" part为DragTarget,它有一个方法
onAccept
,当你拖放Draggable
时它将处理逻辑您可以使用
Draggable
类拖动要拖动的项目,并将其放置或粘贴到屏幕上的某个位置,您必须使用DragTarget
类包装该项目 . 在DragTarget
类onAccept
方法中,您可以在其中编写逻辑 . 你也可以在这里引用我的代码