I'm trying to do a quick pagination example with Jetpack
compose in where I load the first 6 items of the list, then I load another 6 and so on until the end of the list.
I'm aware of the error in the for loop that will cause an IndexOutOfBounds
since is not well designed to iterate until the last element of the array
My problem is two, first the for loop one, I don't know how to take from 0 - 6 , 6 - 12 - 12 - list.size
Then my other problem is that every time I use setList it should recompose the LazyColumnForIndex
and its not, causing only to render the first 6 items
What I'm doing wrong here ?
val longList = mutableListOf("Phone","Computer","TV","Glasses","Cup",
"Stereo","Music","Furniture","Air","Red","Blue","Yellow",
"White","Black","Pink","Games","Car","Motorbike")
@Composable
fun PaginationDemo() {
val maxItemsPerPage = 6
val list = mutableListOf<String>()
var (page,setValue) = remember { mutableStateOf(1) }
val (paginatedList,setList) = remember { mutableStateOf(getPaginatedList(page,maxItemsPerPage, list)) }
LazyColumnForIndexed(items = paginatedList ) { index, item ->
Text(text = item,style = TextStyle(fontSize = 24.sp))
if(paginatedList.lastIndex == index){
onActive(callback = {
setValue(page++)
setList(getPaginatedList(page,maxItemsPerPage,list))
})
}
}
}
private fun getPaginatedList(page:Int,maxItemsPerPage:Int,list:MutableList<String>): MutableList<String> {
val startIndex = maxItemsPerPage * page
for(item in 0 until startIndex){
list.add(longList[item])
}
return list
}