我正在对 LazyColumn 中的列表进行更改,并向 items 属性添加一个键,希望使用新列表刷新 LazyColumn。但 LazyColumn 不刷新。
你有什么建议?
我有以下代码段:
class colNames(
val name:String,
val id:String
)
var colparent:List<colNames> = emptyList<colNames>()
//Process filling the List
var tempList: MutableList<colNames>
//Some code
colparent = tempList.toList()
LazyColumn(modifier = Modifier.padding(top = 36.dp))
{
itemsIndexed(
items = colparent,
key = { _, item -> item.id },
) { ind, item ->
Text(
text = item.name,
modifier = Modifier
.clickable(
onClick = {colparent = reorderNamesList(colparent, ind)} //This is a test function that changes the item position in the list ramdomly by the index
)
)
}
}
我找到了问题的解决方案。
我有:
var colparent by remember { mutableStateOf<List<colNames>>(emptyList<colNames>()) }
然后更改为:
var colparent:List<colNames> = emptyList<colNames>()
都不起作用。最后我找到了一篇文章:“探索 Jetpack Compose LazyList 动画”,其中有一个完整的示例,并注意到问题是我需要一个 MutableStateList 而不仅仅是一个 MutableState。
最终代码为:
val listItems = remember { colparent.toMutableStateList() } //THIS IS THE KEY
LazyColumn(modifier = Modifier.padding(top = 36.dp))
{
itemsIndexed(
items = listItems ,
key = { _, item -> item.id },
) { ind, item ->
Text(
text = item.name,
modifier = Modifier
.clickable(
onClick = {
colparent = reorderNamesList(colparent, ind)
//Above is a test function that changes the item position
//in the list ramdomly by the index
colparent.forEachIndexed { id, x -> listItems[id] = x }
//This is part of the solution.
//Now Modify listItems, since is a State List the LacyColumn key statement
//detects the State change thus the LazyColumn refreshes.
}
)
)
}
}