widget_util.dart 2.1 KB

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