Search code examples
androidandroid-jetpack-composecomposable

Get visible items when scrolling in a LazyList


I have a LazyList and I have to load item information of those items visible on screen. Every time a new item is visible (because the user scrolled) it should load the item information. What would be the right approach?

I know LazyGridState / LazyListState have layoutInfo.visibleItemsInfo but I'm more concerned about the way to consume this information.

I suppose I should use a LaunchedEffect to trigger my "callback" but what should be the key? the "listState"? Or should I use a derivedStateOf?


Solution

  • You can use a side-effect to know what are the visible items in any time.

    Something like:

    LaunchedEffect(visibleItemIds){
       //doSomething()
    }
    
    val state = rememberLazyListState()
    val visibleItemIds: List<Int> by remember {
        derivedStateOf {
            val layoutInfo = state.layoutInfo
            val visibleItemsInfo = layoutInfo.visibleItemsInfo
            if (visibleItemsInfo.isEmpty()) {
                emptyList()
            } else {
                visibleItemsInfo.map { it.index }
            }
        }
    }
    

    Note that visibleItemsInfo returns also the partially visible items.