widget_util.dart 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'package:flutter/widgets.dart';
  2. import 'package:flutter/rendering.dart';
  3. /**
  4. * @Author: thl
  5. * @GitHub: https://github.com/Sky24n
  6. * @Description: Widget Util.
  7. * @Date: 2018/9/10
  8. */
  9. ///
  10. class WidgetUtil {
  11. bool _hasMeasured = false;
  12. double _width;
  13. double _height;
  14. /// Widget rendering listener.
  15. /// Widget渲染监听
  16. /// context: Widget context
  17. /// isOnce: true,Continuous monitoring false,Listen only once.
  18. /// onCallBack: Widget Rect CallBack
  19. void asyncPrepare(
  20. BuildContext context, bool isOnce, ValueChanged<Rect> onCallBack) {
  21. if (_hasMeasured) return;
  22. WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) {
  23. RenderBox box = context.findRenderObject();
  24. if (box != null && box.semanticBounds != null) {
  25. if (isOnce) _hasMeasured = true;
  26. double width = box.semanticBounds.width;
  27. double height = box.semanticBounds.height;
  28. if (_width != width || _height != height) {
  29. _width = width;
  30. _height = height;
  31. if (onCallBack != null) onCallBack(box.semanticBounds);
  32. }
  33. }
  34. });
  35. }
  36. ///get Widget Bounds (width, height, left, top, right, bottom and so on).Widgets must be rendered completely.
  37. ///获取widget Rect
  38. static Rect getWidgetBounds(BuildContext context) {
  39. RenderBox box = context.findRenderObject();
  40. return (box != null && box.semanticBounds != null)
  41. ? box.semanticBounds
  42. : Rect.zero;
  43. }
  44. ///Get the coordinates of the widget on the screen.Widgets must be rendered completely.
  45. ///获取widget在屏幕上的坐标,widget必须渲染完成
  46. static Offset getWidgetLocalToGlobal(BuildContext context) {
  47. RenderBox box = context.findRenderObject();
  48. return box == null ? Offset.zero : box.localToGlobal(Offset.zero);
  49. }
  50. }