attach method

void attach(
  1. HTMLElement element
)

Attaches the controller to a rendered HTML element.

Implementation

void attach(HTMLElement element) {
  detach();

  if (!isElementScrollable(element)) {
    throw StateError(
      'Only scrollable components like Row, Column, ListView, GridView, '
      'or the like can be attached to a ScrollController.',
    );
  }

  // store the scrollable element
  _attachedElement = element;

  // update scroll position to initial offset
  if (direction == ScrollDirection.vertical) {
    _attachedElement!.scrollTop = _offset;
  } else {
    _attachedElement!.scrollLeft = _offset;
  }

  // listen to scroll events
  _subscription = EventStreamProviders.scrollEvent
      .forTarget(_attachedElement!)
      .listen((_) {
        _offset = (direction == ScrollDirection.vertical
            ? _attachedElement!.scrollTop
            : _attachedElement!.scrollLeft);
        notifyListeners();
      });
}