Skip to content

Instantly share code, notes, and snippets.

@vovahost
Created November 14, 2019 10:45
Show Gist options
  • Save vovahost/6039389796237551b5735d2e94e17489 to your computer and use it in GitHub Desktop.
Save vovahost/6039389796237551b5735d2e94e17489 to your computer and use it in GitHub Desktop.
Get widget's absolute coordinates on a screen in Flutter
// You can use this extension I wrote (requires Dart 2.6):
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:
final containerKey = GlobalKey();
Rect get containerRect => containerKey.globalPaintBounds;
Container(
key: containerKey,
width: 100,
height: 50,
)
void printContainerWidgetGlobalRect() {
print('rect: ${containerRect}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment