nativeFindWidgetPositionByLabel static method

Future<Map<String, dynamic>> nativeFindWidgetPositionByLabel({
  1. required String label,
  2. required num scaleX,
  3. required num scaleY,
  4. num? statusBarHeight,
  5. required Size screenSize,
})

Implementation

static Future<Map<String, dynamic>> nativeFindWidgetPositionByLabel({
  required String label,
  required num scaleX,
  required num scaleY,
  num? statusBarHeight,
  required Size screenSize,
}) async {
  final GlobalKey? key = _widgetKeys[label];

  if (key != null && key.currentContext != null) {
    // Check if the widget is currently scrolling
    bool isScrolling = await _checkPageScrollStatus(key);
    if (isScrolling) {
      NLogger.w(
        'Widget with label $label is currently scrolling, cannot track position',
      );
      return {
        'result': false,
        'message': 'Widget is currently scrolling',
      };
    }

    // Check widget stability with circuit breaker
    bool isStable = await _isWidgetStable(
      key,
      label,
      checkInterval: const Duration(milliseconds: 100),
      stabilityDuration: const Duration(seconds: 1),
    );

    if (!isStable) {
      NLogger.w(
        'Widget with label $label is not stable, position may have changed',
      );
      return {
        'result': false,
        'message': 'Widget position changed during tracking',
      };
    }

    // Get the final stable position
    RenderBox box = key.currentContext!.findRenderObject() as RenderBox;
    Offset position = box.localToGlobal(Offset.zero);

    // if position is out of bounds, return false
    if (position.dx < 0 ||
        position.dy < 0 ||
        position.dx + box.size.width > screenSize.width ||
        position.dy + box.size.height > screenSize.height ||
        box.size.height == 0 ||
        box.size.width == 0) {
      NLogger.w(
        'Widget position for label $label is out of bounds: $position, size: ${box.size}',
      );
      return {
        'result': false,
        'message': 'Widget position is partially or completely out of bounds',
      };
    }

    NLogger.i('Finding widget position for label: $label');

    NLogger.i(
      'Widget position for label $label: x=${position.dx}, y=${position.dy}, width=${box.size.width}, height=${box.size.height}',
    );

    return {
      'result': true,
      'x': position.dx * scaleX,
      'y': position.dy * scaleY + (statusBarHeight ?? 0),
      'width': box.size.width * scaleX,
      'height': box.size.height * scaleY,
    };
  } else {
    return {
      'result': false,
    };
  }
}