flutter 简单封装一个widget控件

简单来说就是定义一个布局,在里面的build做好接收widget的写法,要用到时传进来即可

WPopupMenu(
  onValueChanged: (int value) {
    
    
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(actions[value]),
      duration: Duration(milliseconds: 500),
    ));
  },
  pressType: PressType.longPress,
  actions: actions,
  key: null,
  child: UnconstrainedBox(//有传一个child进去
    child: Container(
      height: 40,
      color: Colors.cyan,
      alignment: Alignment.center,
      child: Text(
        '我是Title $index',
        style: TextStyle(color: Colors.white),
      ),
    ),
  ),
),

class WPopupMenu extends StatefulWidget {
    
    
  WPopupMenu({
    
    
     Key? key,
    required this.onValueChanged,
    required this.actions,
    required this.child,
    this.pressType = PressType.longPress,
    this.pageMaxChildCount = 5,
    this.backgroundColor = Colors.black,
    this.menuWidth = 250,
    this.menuHeight = 42,
  });

  final ValueChanged<int> onValueChanged;
  final List<String> actions;
  final Widget child;
  final PressType pressType; // 点击方式 长按 还是单击
  final int pageMaxChildCount;
  final Color backgroundColor;
  final double menuWidth;
  final double menuHeight;

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

class _WPopupMenuState extends State<WPopupMenu> {
    
    
   double? width;
   double? height;
  var button;
   var overlay;
  OverlayEntry? entry;

  @override
  void initState() {
    
    
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((call) {
    
    
      width = context.size?.width??0;
      height = context.size?.height??0;
      button = context.findRenderObject();
      overlay = Overlay.of(context)?.context.findRenderObject();
    });
  }

  @override
  Widget build(BuildContext context) {
    
    
    return WillPopScope(
      onWillPop: () {
    
    
        removeOverlay();
        return Future.value(true);
      },
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: widget.child,//在这里接收传进来的那个child就可以了
        onTap: () {
    
    
          if (widget.pressType == PressType.singleClick) {
    
    
            onTap();
          }
        },
        onLongPress: () {
    
    
          if (widget.pressType == PressType.longPress) {
    
    
            onTap();
          }
        },
      ),
    );
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_44911775/article/details/129301763