How to use jetpack compose paging with LazyVerticalGrid

Issue

I am trying to display paged items using LazyVerticalGrid. The code I am trying is shown below.

 val categories = repo.categories.collectAsLazyPagingItems()

 LazyVerticalGrid(
    cells = GridCells.Fixed(2),
    modifier = Modifier.padding(8.dp)
 ) {

      items(categories) { category ->
          Box(Modifier.padding(8.dp)) {
              CategoryView(category)
          }
      }

 }

Please note that I have imported androidx.paging.compose.items and androidx.paging.compose.collectAsLazyPagingItems. Also categories is of type LazyPagingItems<Category>.

It works perfectly with LazyColumn and LazyRow but not LazyVerticalGrid.
The error I am getting is:

Type mismatch.
Required:
Int
Found:
LazyPagingItems<Category>

Solution

I came up with a solution by writing an extension function for LazyGridScope like the one written for LazyListScope in the androidx.paging:paging-compose library.

@ExperimentalFoundationApi
public fun <T: Any> LazyGridScope.items(
    lazyPagingItems: LazyPagingItems<T>,
    itemContent: @Composable LazyItemScope.(value: T?) -> Unit
) {
    items(lazyPagingItems.itemCount) { index ->
        itemContent(lazyPagingItems[index])
    }
}

Answered By – Olu Udeh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published