描述:

使用Draggable 实现组件的拖拽效果(LongPressDraggable长按拖拽组件属性类似Draggable)

效果图:

代码:


class DraggablePositionPage extends StatefulWidget {
  const DraggablePositionPage({Key? key}) : super(key: key);

  @override
  State<DraggablePositionPage> createState() => _DraggablePositionPageState();
}

class _DraggablePositionPageState extends State<DraggablePositionPage> {
  double _left = 0;
  double _top = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Draggable"),
        ),
        body: Stack(
          children: [
            Positioned(
              left: _left,
              top: _top,
              child: Draggable(
                //用于限制child可移动的方向,默认null允许任何方向
                // axis: null,
                child: _buildDraggable(context),
                //拖动时的部件
                feedback: _buildDraggable(context),
                //拖动时,child部件的显示样式
                childWhenDragging: Container(height: 100, width: 100),

                //开始拖动时回调
                onDragStarted: () {
                  print("----------onDragStarted");
                },
                //拖动中的回调
                onDragUpdate: (details) {
                  print("----------onDragUpdate");
                  // print(details.localPosition.dy);
                },
                //拖动结束时回调
                onDragEnd: (details) {
                  print("----------onDragEnd");
                  //details.offset.dy的值包含状态栏和appbar的高度,所以我们最终的top=dy-状态栏高度-appbar高度
                  setState(() {
                    _left = details.offset.dx;
                    _top = details.offset.dy -
                        MediaQuery.of(context).padding.top -
                        56;
                  });
                },
              ),
            )
          ],
        ));
  }

  Widget _buildDraggable(BuildContext context) {
    return Container(
      height: 100,
      width: 100,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.teal,
        borderRadius: BorderRadius.circular(4),
      ),
    );
  }
}

注意:

details.offset.dy的值包含状态栏和appbar的高度

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐