Jetpack Compose 不在 setValue 上重组可组合

Jetpack Compose not recomposing composable on setValue

我正在尝试使用 Jetpack compose 做一个快速分页示例,我在其中加载列表的前 6 项,然后加载另外 6 项,依此类推,直到列表末尾。

我知道 for 循环中的错误会导致 IndexOutOfBounds,因为设计不当,无法迭代到数组的最后一个元素

我的问题有两个,第一个是 for 循环,我不知道如何取自 0 - 6 , 6 - 12 - 12 - list.size

然后我的另一个问题是,每次我使用 setList 时,它应该重新组合 LazyColumnForIndex 而不是,导致只渲染前 6 个项目

我做错了什么?

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
}

这似乎有效。

@Composable
fun PaginationDemo() {
    val maxItemsPerPage = 6
    val list = mutableStateListOf<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),
            modifier = Modifier
                .fillParentMaxWidth()
                .height((ConfigurationAmbient.current.screenHeightDp / 3).dp)
                .background(color = Color.Blue)
        )
        Divider(thickness = 2.dp)

        Log.d("MainActivity", "lastIndex = ${paginatedList.lastIndex} vs index = $index")
        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 maxSize = longList.size
    val startIndex = if (maxItemsPerPage * page >= maxSize) maxSize else maxItemsPerPage * page
    list.clear()
    for(item in 0 until startIndex){
        list.add(longList[item])
    }

    return list
}