scrollToComponent method

void scrollToComponent(
  1. String id, {
  2. Duration duration = const Duration(milliseconds: 300),
  3. Curves curve = Curves.easeInOut,
})

Scrolls to a specific component inside the scrollable component.

The component to scroll to, identified by a unique id, should be a child of the scrollable component and not a scrollable component itself.

Animation will be ignored when duration is zero.

Example

final scrollController = ScrollController();
scrollController.scrollToComponent('some-id');

Implementation

void scrollToComponent(
  String id, {
  Duration duration = const Duration(milliseconds: 300),
  Curves curve = Curves.easeInOut,
}) {
  if (_attachedElement == null) return;

  final target = _attachedElement!.querySelector('#$id') as HTMLElement?;

  if (target != null) {
    double targetOffset;

    // get target and container positions
    final containerRect = _attachedElement!.getBoundingClientRect();
    final targetRect = target.getBoundingClientRect();

    // calculate target offset
    if (direction == ScrollDirection.vertical) {
      final relativeTop = targetRect.top - containerRect.top;
      targetOffset = _attachedElement!.scrollTop + relativeTop;
    } else {
      final relativeLeft = targetRect.left - containerRect.left;
      targetOffset = _attachedElement!.scrollLeft + relativeLeft;
    }

    // animate to target offset
    animateTo(
      targetOffset,
      duration: duration,
      curve: curve,
    );
  }
}