如何在 Flutter 中实现可滚动拖放?

Mys*_*233 6 flutter flutter-layout

我正在尝试使用 SingleChildScrollView 制作可滚动和可缩放的堆栈,以实现画布编辑器。

当我将可拖动项目放入初始视图中时,拖放效果非常好,但是当我向下滚动视图并尝试放下容器时,拖放会返回到初始视图中。

我是 Flutter 开发的新手,所以也许我在实现这样的事情时误解了。

这是我目前拥有的代码。

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: App(),
      ),
    );
  }
}

class App extends StatefulWidget {
  @override
  AppState createState() => AppState();
}

class AppState extends State<App> {
  Color caughtColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Stack(
        children: <Widget>[
          Container(
            height: 2000,
          ),
          DragBox(Offset(0.0, 0.0), 'Box One', Colors.blueAccent),
        ],
      ),
    );

  }
}

class DragBox extends StatefulWidget {
  final Offset initPos;
  final String label;
  final Color itemColor;

  DragBox(this.initPos, this.label, this.itemColor);

  @override
  DragBoxState createState() => DragBoxState();
}

class DragBoxState extends State<DragBox> {
  Offset position = Offset(0.0, 0.0);

  @override
  void initState() {
    super.initState();
    position = widget.initPos;
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
        left: position.dx,
        top: position.dy,
        child: Draggable(
          data: widget.itemColor,
          child: Container(
            width: 100.0,
            height: 100.0,
            color: widget.itemColor,
            child: Center(
              child: Text(
                widget.label,
                style: TextStyle(
                  color: Colors.white,
                  decoration: TextDecoration.none,
                  fontSize: 20.0,
                ),
              ),
            ),
          ),
          onDraggableCanceled: (velocity, offset) {
            setState(() {
              position = offset;
            });
          },
          feedback: Container(
            width: 120.0,
            height: 120.0,
            color: widget.itemColor.withOpacity(0.5),
            child: Center(
              child: Text(
                widget.label,
                style: TextStyle(
                  color: Colors.white,
                  decoration: TextDecoration.none,
                  fontSize: 18.0,
                ),
              ),
            ),
          ),
        ));
  }
}
Run Code Online (Sandbox Code Playgroud)

任何建议或代码示例都会对我非常有帮助。

小智 4

我这样解决问题,用监听器包装你的可拖动对象。

Listener listenableDraggable = Listener(
  child: draggable,
  onPointerMove: (PointerMoveEvent event) {
    if (event.position.dy > MediaQuery.of(context).size.height) {
      // 120 is height of your draggable.
      scrollController.scrollTo(scrollcontroller.offset + 120);
    }
  },
);
Run Code Online (Sandbox Code Playgroud)