首页 > 解决方案 > 使 Draggable 在取消时不返回

问题描述

我正在尝试创建一个可以在屏幕上拖动的可拖动容器。我面临的问题是 Draggable 总是回到它的 prevouis 位置。https://imgur.com/a/0ESoCZW 那么,您如何创建停留在您手指左手位置的 Draggable。

标签: flutterdart

解决方案


您可以使用onDraggableCanceled属性来更改位置。

我希望下面的例子能清除你的想法。

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  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(
                  "currently dragging",
                  style: Theme.of(context).textTheme.headline,
                ),
              ),
              color: Colors.blue[300],
              width: width,
              height: height,
            ),
            onDraggableCanceled: (Velocity velocity, Offset offset) {
              setState(() => position = offset);
            },
          ),
        ),
      ],
    );
  }
}

推荐阅读