Want to get widget’s absolute coordinates on a screen in Flutter? You can use the below extension to get widget’s absolute coordinates on a screen.
1 2 3 4 5 6 7 8 9 10 11 12 | extension GlobalKeyEx 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:
1 2 3 4 5 6 7 8 9 10 11 12 | final containerKey = GlobalKey(); Rect get containerRect => containerKey.globalPaintBounds; Container( key: containerKey, width: 100, height: 50, ) void printWidgetPosition() { print('absolute coordinates on screen: ${containerRect}'); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.