updateSelectorPositionIfNeeded method

void updateSelectorPositionIfNeeded({
  1. required Widget selectorWidget,
  2. bool expanded = true,
})

Monitors and updates the position of the dropdown selector widget if needed.

This method checks the position of the dropdown using its current global offset. If the position has changed since the last check, the suggestions are either closed or reopened, depending on the direction of the movement and the expansion state of the suggestions.

  • If the dropdown has moved horizontally, it closes the suggestions immediately.
  • If the dropdown has moved vertically and the suggestions are expanded, it temporarily closes them and then reopens them after a short delay.

It also ensures that the method continues to check for future position changes by adding a post-frame callback.

Parameters:

  • selectorWidget: The dropdown selector widget that needs position adjustments.

Implementation

void updateSelectorPositionIfNeeded({
  required Widget selectorWidget,
  bool expanded = true,
}) {
  if ((this.suggestionsExpanded || _suggestionClosedOnMove) &&
      dropdownKey.currentContext != null) {
    final RenderBox renderBox =
        dropdownKey.currentContext!.findRenderObject() as RenderBox;
    final Offset currentOffset = renderBox.localToGlobal(Offset.zero);

    _previousOffset ??= currentOffset;

    if (_previousOffset != currentOffset) {
      _timer?.cancel();
      if (_previousOffset!.dx != currentOffset.dx) {
        closeSuggestions();
      } else {
        if (suggestionsExpanded) {
          closeSuggestions();
          _suggestionClosedOnMove = true;
        }
        if (_suggestionClosedOnMove) {
          _timer = Timer(const Duration(milliseconds: 100), () {
            _suggestionClosedOnMove = false;
            expandSuggestions(
              selectorWidget: selectorWidget,
              expanded: expanded,
            );
          });
        }
      }

      _previousOffset = currentOffset;
    }
  }

  // Continue to check for future changes
  WidgetsBinding.instance.addPostFrameCallback((_) {
    updateSelectorPositionIfNeeded(
      selectorWidget: selectorWidget,
      expanded: expanded,
    );
  });
}