widget_location_util.dart 876 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import 'package:flutter/cupertino.dart';
  2. /// 组件位置工具类
  3. class WidgetLocationUtil {
  4. /// 获取组件的位置信息
  5. static WidgetInfo getWidgetLocation(GlobalKey key) {
  6. final context = key.currentContext;
  7. if (context == null) {
  8. throw Exception('Context is null');
  9. }
  10. final renderObject = context.findRenderObject();
  11. if (renderObject == null || renderObject is! RenderBox) {
  12. throw Exception('RenderObject is null or not a RenderBox');
  13. }
  14. final offset = renderObject.localToGlobal(Offset.zero);
  15. final size = renderObject.size;
  16. return WidgetInfo(offset, size);
  17. }
  18. }
  19. /// 组件信息
  20. class WidgetInfo {
  21. // 位置
  22. final Offset position;
  23. // 大小
  24. final Size size;
  25. WidgetInfo(this.position, this.size);
  26. @override
  27. String toString() {
  28. return 'WidgetInfo{position: $position, size: $size}';
  29. }
  30. }