Flutter GlobalKey用处

拖动示例

class DragWidget extends StatefulWidget{
  @override
  _DragWidgetState createState() {
    // TODO: implement createState
    return _DragWidgetState();
  }
}

class _DragWidgetState extends State<DragWidget> {
  GlobalKey stackKey = GlobalKey();
  GlobalKey btnKey = GlobalKey();
  double _left = 0.0;
  double _top = 0.0;
  double _areaWidth = 0.0;
  double _areaHeight = 0.0;
  
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((duration) {
      setState(() {
        _areaWidth = stackKey.currentContext.size.width - btnKey.currentContext.size.width;
        _areaHeight = stackKey.currentContext.size.height - btnKey.currentContext.size.height;
      });
    });
  }
  
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Stack(
      key: stackKey,
      children: <Widget>[
        Positioned(
          top: _top,
          left: _left,
          child: GestureDetector(
            child: FloatingActionButton(
              key: btnKey,
              child: Text('drag'),
            ),
            onPanUpdate: (e) {
              setState(() {
                _left += e.delta.dx;
                _top += e.delta.dy;
                if (_left < 0) {
                  _left = 0;
                } else if (_left > _areaWidth) {
                  _left = _areaWidth;
                }
                if (_top < 0) {
                  _top = 0;
                } else if (_top > _areaHeight) {
                  _top = _areaHeight;
                }
              });
            },
          )
        )
      ],
    );
  }
}

效果展示

    将onPanUpdate改为onVerticalDragUpdate即可变为只能在竖直方向上拖动,onHorizontalDragUpdate同理。

三、缩放
class ScaleWidget extends StatefulWidget{
  @override
  _ScaleWidgetState createState() {
    // TODO: implement createState
    return _ScaleWidgetState();
  }
}
class _ScaleWidgetState extends State<ScaleWidget>{
  double _width = 300.0;
  double _height = 200.0;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
      child: GestureDetector(
        child: Container(
          constraints: BoxConstraints.tight(Size(_width, _height)),
          color: Colors.blue,
        ),
        onScaleUpdate: (e) {
          print(e);
          setState(() {
            // 限制宽度缩放比例在0.7-1.2之间,如果超过这个范围,Container会变为原来的大小
            _width = 300* e.scale.clamp(0.7, 1.2);
            _height = 200*e.scale.clamp(0.7, 1.2);
          });
        },
      )
    );
  }
}

Flutter GlobalKey的使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值