widget_util.dart 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
part of cool_ui;
/**
 * @Author: thl
 * @GitHub: https://github.com/Sky24n
 * @JianShu: https://www.jianshu.com/u/cbf2ad25d33a
 * @Email: 863764940@qq.com
 * @Description: Widget Util.
 * @Date: 2018/9/10
 */

/// Widget Util.
class _WidgetUtil {
  bool _hasMeasured = false;
Kevin's avatar
Kevin committed
14 15
  double? _width;
  double? _height;
16 17 18 19 20 21 22 23 24

  /// Widget rendering listener.
  /// Widget渲染监听.
  /// context: Widget context.
  /// isOnce: true,Continuous monitoring  false,Listen only once.
  /// onCallBack: Widget Rect CallBack.
  void asyncPrepare(
      BuildContext context, bool isOnce, ValueChanged<Rect> onCallBack) {
    if (_hasMeasured) return;
Kevin's avatar
Kevin committed
25
    WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) {
Kevin's avatar
Kevin committed
26
      RenderBox? box = context.findRenderObject() as RenderBox?;
27 28 29 30 31 32 33 34 35 36 37 38 39 40
      if (box != null && box.semanticBounds != null) {
        if (isOnce) _hasMeasured = true;
        double width = box.semanticBounds.width;
        double height = box.semanticBounds.height;
        if (_width != width || _height != height) {
          _width = width;
          _height = height;
          if (onCallBack != null) onCallBack(box.semanticBounds);
        }
      }
    });
  }

  /// Widget渲染监听.
Kevin's avatar
Kevin committed
41
  void asyncPrepares(bool isOnce, ValueChanged<Rect?>? onCallBack) {
42
    if (_hasMeasured) return;
Kevin's avatar
Kevin committed
43
    WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) {
44 45 46 47 48 49 50 51
      if (isOnce) _hasMeasured = true;
      if (onCallBack != null) onCallBack(null);
    });
  }

  ///get Widget Bounds (width, height, left, top, right, bottom and so on).Widgets must be rendered completely.
  ///获取widget Rect
  static Rect getWidgetBounds(BuildContext context) {
Kevin's avatar
Kevin committed
52
    RenderBox? box = context.findRenderObject() as RenderBox?;
Kevin's avatar
Kevin committed
53
    return (box != null) ? box.semanticBounds : Rect.zero;
54 55 56 57 58
  }

  ///Get the coordinates of the widget on the screen.Widgets must be rendered completely.
  ///获取widget在屏幕上的坐标,widget必须渲染完成
  static Offset getWidgetLocalToGlobal(BuildContext context) {
Kevin's avatar
Kevin committed
59
    RenderBox? box = context.findRenderObject() as RenderBox?;
60 61
    return box == null ? Offset.zero : box.localToGlobal(Offset.zero);
  }
Kevin's avatar
Kevin committed
62
}