Flutter自定义可拖动组件

Flutter自定义可拖动组件_第1张图片

 WidgetsBinding.instance.addPostFrameCallback((_) async {
      Overlay.of(context)?.insert(_entry());
    });
  OverlayEntry _entry() {
    return OverlayEntry(builder: (ctx) {
      return DraggableComponentOrderStatuWidget(
          Offset(ctx.width - 100, ctx.height / 3));
    });
  }
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:upower/common/style/common_style.dart';

class DraggableComponentOrderStatuWidget extends StatefulWidget {
  DraggableComponentOrderStatuWidget(this.offsetParam, {super.key});

  Offset offsetParam;

  @override
  State<DraggableComponentOrderStatuWidget> createState() =>
      _DraggableComponentOrderStatuWidgetState();
}

class _DraggableComponentOrderStatuWidgetState
    extends State<DraggableComponentOrderStatuWidget> {
  Offset? _offset;

  Widget _getContentWidget() {
    return Container(
      alignment: Alignment.center,
      width: 100,
      height: 30,
      decoration: const BoxDecoration(
        color: ColorStyle.primaryC2,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(15), bottomLeft: Radius.circular(15)),
      ),
      child: Text(
        "租赁中",
        style: TextStyle(
            fontSize: 12.sp,
            color: Colors.white,
            decoration: TextDecoration.none),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _offset = widget.offsetParam;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          right: 0,
          top: _offset?.dy,
          child: Draggable(
            feedback: _getContentWidget(),
            childWhenDragging: Text(""), // 设置为null以隐藏原始小部件
            onDraggableCanceled: (velocity, offset) {
              setState(() {
                _offset = offset;
              });
            },
            child: _getContentWidget(),
          ),
        ),
      ],
    );
  }
}

你可能感兴趣的:(Flutter,flutter)