Flutter LongPressDraggable Widget使用详解

Flutter LongPressDraggable Widget是Flutter中可拖拽的widget之一,可以用来实现在长按并拖动时移动widget的效果。本文将详细介绍Flutter LongPressDraggable Widget的使用方法和注意事项。

LongPressDraggable简介

Flutter LongPressDraggable Widget继承自Draggable Widget,可以在长按并拖动时移动widget,支持拖动前后位置的回调,以及是否允许拖动的控制。

在使用LongPressDraggable Widget时,需要将需要拖动的widget包裹在Draggable Widget中,并指定child和feedback参数。

  • child:用于展示原始的widget。
  • feedback:用于在拖拽时显示的widget。

此外,还需要指定onDraggableCanceled和onDraggableCompleted两个回调函数。

  • onDraggableCanceled:当拖动被取消时调用,可以用于进行清理操作。
  • onDraggableCompleted:当拖动完成时调用,可以用于处理拖动完成后的操作。
  • LongPressDraggable Widget示例

下面是一个简单的LongPressDraggable Widget示例,当长按widget时可以拖动它,松开手指时会回到原始位置。

class LongPressDraggableWidget extends StatefulWidget {
  @override
  _LongPressDraggableWidgetState createState() =>
      _LongPressDraggableWidgetState();
}

class _LongPressDraggableWidgetState extends State<LongPressDraggableWidget> {
  bool _canDrag = true;
  Offset _offset = Offset.zero;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('LongPressDraggable Widget'),
      ),
      body: Center(
        child: LongPressDraggable(
          child: Container(
            width: 100,
            height: 100,
            color: Colors.blue,
            child: Center(
              child: Text(
                'LongPressDraggable',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
          feedback: Container(
            width: 120,
            height: 120,
            color: Colors.blue.withOpacity(0.5),
            child: Center(
              child: Text(
                'LongPressDraggable',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
          onDraggableCanceled: (Velocity velocity, Offset offset) {
            setState(() {
              _offset = offset;
            });
          },
          onDraggableCompleted: () {
            setState(() {
              _offset = Offset.zero;
            });
          },
          childWhenDragging: Container(
            width: 100,
            height: 100,
            color: Colors.grey,
            child: Center(
              child: Text(
                'LongPressDraggable',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
          canDrag: _canDrag,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _canDrag = !_canDrag;
          });
        },
        child: Icon(Icons.lock),
      ),
    );
  }
}

在这个示例中,创建了一个可以长按并拖动的Container,当拖动被取消时记录偏移量,当拖动完成时恢复原始位置。

powered by Gitbook© 2023 编外计划 | 最后修改: 2023-11-24 03:37:00

results matching ""

    No results matching ""