scrollToElement function

void scrollToElement(
  1. Element element, {
  2. bool centered = true,
  3. bool vertical = true,
  4. bool horizontal = true,
  5. bool smooth = true,
  6. int? translateX,
  7. int? translateY,
  8. Object? scrollable,
})

Scrolls the viewport to the element.

  • If centered is true, tries to center the element in the viewport.
  • If vertical is true only does a vertical scroll.
  • If horizontal is true only does a horizontal scroll.
  • If smooth is true does a smooth scroll animation.
  • scrollable is the element to scroll. If null it will be the window or the body, identifying which one is scrolled.

Implementation

void scrollToElement(
  Element element, {
  bool centered = true,
  bool vertical = true,
  bool horizontal = true,
  bool smooth = true,
  int? translateX,
  int? translateY,
  Object? scrollable,
}) {
  var pos = getElementDocumentPosition(element);

  var x = pos.a;
  var y = pos.b;

  if (translateX != null) {
    x += translateX;
  }

  if (translateY != null) {
    y += translateY;
  }

  if (centered) {
    var w = window.innerWidth ?? 0;
    var h = window.innerHeight ?? 0;

    x = max(0, x - (w ~/ 2));
    y = max(0, y - (h ~/ 2));
  }

  scrollTo(
    horizontal ? x : null,
    vertical ? y : null,
    smooth: smooth,
    scrollable: scrollable,
  );
}