在Flutter中获取小部件在屏幕上的绝对坐标

2023-09-11  本文已影响0人  magicL1

给globalkey增加一个扩展

extension GlobalKeyExtension on GlobalKey {

  Rect? get globalPaintBounds {

    final renderObject = currentContext?.findRenderObject();

    final matrix = renderObject?.getTransformTo(null);

    if (matrix != null && renderObject?.paintBounds != null) {

        final rect = MatrixUtils.transformRect(matrix, renderObject!.paintBounds);

        return rect;

    } else {

        return null;

    } } }

使用方法

final containerKey = GlobalKey();

Container(

    key: containerKey,

    width: 100,

    height: 50,

)

void printWidgetPosition()

{

    print('absolute coordinates on screen: ${containerKey.globalPaintBounds}');

}

上一篇 下一篇

猜你喜欢

热点阅读