美文网首页
在Flutter中获取小部件在屏幕上的绝对坐标

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

作者: magicL1 | 来源:发表于2023-09-11 16:17 被阅读0次

给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}');

}

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/vcoevdtx.html