How to get widget's absolute coordinates on a screen in Flutter?

后端 未结 2 474
野的像风
野的像风 2021-01-04 02:56

How to get widget\'s absolute coordinates on a screen in Flutter?

Or its offset in a parent

Example:

import \'package:flutter/material.dart\'         


        
相关标签:
2条回答
  • 2021-01-04 03:00

    Maybe this simple widget is what you want : rect_getter 0.0.1

    This is a widget provide a simple way to get child's rectangle information after rendered.

    demo

    0 讨论(0)
  • 2021-01-04 03:25

    You can use this extension I wrote (requires Dart 2.6):

    extension GlobalKeyExtension on GlobalKey {
      Rect get globalPaintBounds {
        final renderObject = currentContext?.findRenderObject();
        var translation = renderObject?.getTransformTo(null)?.getTranslation();
        if (translation != null && renderObject.paintBounds != null) {
          return renderObject.paintBounds
              .shift(Offset(translation.x, translation.y));
        } else {
          return null;
        }
      }
    }
    

    Example how to use it:

    final containerKey = GlobalKey();
    
    Container(
      key: containerKey,
      width: 100,
      height: 50,
    )
    
    void printWidgetPosition() {
      print('absolute coordinates on screen: ${containerKey.globalPaintBounds}');
    }
    
    0 讨论(0)
提交回复
热议问题