如何在 Flutter 中移动屏幕中的小部件

6 move dart flutter flutter-widget

我正在使用颤振,我有一个使用此代码的圆形容器

new Container(
 width: 50.0,
  height: 50.0,
   decoration: new BoxDecoration(
   shape: BoxShape.circle)
Run Code Online (Sandbox Code Playgroud)

我想让这个圆圈像这样在屏幕上移动

在此处输入图片说明

我怎样才能做到这一点?

小智 6

这里是:

import 'package:flutter/material.dart';

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Drag app"),
        ),
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  double width = 100.0, height = 100.0;
  Offset position ;

  @override
  void initState() {
    super.initState();
    position = Offset(0.0, height - 20);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Positioned(
          left: position.dx,
          //top: position.dy - height + 20,
          child: Draggable(
            child: Container(
              width: width,
              height: height,
              color: Colors.blue,
              child: Center(child: Text("Drag", style: Theme.of(context).textTheme.headline,),),
            ),
            feedback: Container(
              child: Center(
                child: Text("Drag", style: Theme.of(context).textTheme.headline,),),
              color: Colors.red[800],
              width: width,
              height: height,
            ),
            onDraggableCanceled: (Velocity velocity, Offset offset){
              setState(() => position = offset);
            },
          ),
        ),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


azi*_*iza 4

您正在寻找的是Draggable小部件。然后,您可以使用传递的翻译onDraggableCanceled和可用于更新放置的偏移量来处理翻译

onDraggableCanceled :(velocity,offset){ 
//update the position here
} 
Run Code Online (Sandbox Code Playgroud)

更新

检查图像后,您将需要“将我放在这里”部分作为DragTarget,它具有一个方法onAccept,可以在您拖放您的图像时处理逻辑。Draggable

  • `onDraggableCanceled` 在这里是不必要的。他想要的是一个`DragTarget`。 (2认同)