Search code examples
vaadinvaadin-flow

Component VirtualList, scroll programatically to the end of the list


Included in the page is a VirtualList like in the sample page

VirtualList<Person> list = new VirtualList<>();
list.setItems(people);
list.setRenderer(personCardRenderer);
add(list);

The list itself contains many items and items will be periodically added to the end of the list. I initially want to show the last items of list.

I'm unable to find an API to scroll either to a specific index nor to the end of the list. Neither trying to scroll via Javascript was successfull. Does exists a solution for this problem or is the (very fast) VirtualList the right component?


Solution

  • Looking at the element documentation, there is a method, scrollToIndex. Looking at the Java API documentation, there is no Java API to call this method.

    You can still call it like so:

    list.getElement().callJsFunction("scrollToIndex", INDEX);
    

    If you plan on doing this often, make a utility method, or, better yet, extend VirtualList and use your class instead, e.g.:

    public class MyVirtualList<T> extends VirtualList<T> {
      ...constructors
    
      // Could just return `void`.
      public PendingJavaScriptResult scrollToIndex(int index) {
        return getElement().callJsFunction("scrollToIndex", index);
      }
    }
    

    I reported the missing Java API for scrollToIndex and a PR was opened: https://github.com/vaadin/flow-components/pull/4451.