gpt4 book ai didi

android - Jetpack 撰写 : LazyColumn not updating with MutableList

转载 作者:行者123 更新时间:2023-12-05 02:25:58 26 4
gpt4 key购买 nike

我正在尝试使用 Jetpack Compose 在单击按钮时删除文本,但 UI 未更新

我尝试设置一个按钮,然后单击一个按钮,deletedTasks 得到更新,如果我的任务在 deletedTasks 中,那么它应该显示一个删除线.

此更改仅手动发生,但我希望它是自动的

我不知道该怎么做。这是我第一次尝试 Jetpack Compose,我们将不胜感激

@Composable
fun toDoItem(title: String, category: String, task: Task) {

val rememberTask = remember { mutableStateOf(deletedTasks) }

Surface(...) {

Column (...) {

Row {
Column (...) {
if (!deletedTasks.contains(task)){
Text(text = title, style = MaterialTheme.typography.h4.copy(
fontWeight = FontWeight.Bold
))
} else {
Text(text = title, style = MaterialTheme.typography.h4.copy(
fontWeight = FontWeight.Bold
), textDecoration = TextDecoration.LineThrough)
}
}
IconButton(onClick = {
rememberTask.value.add(task)
}) {
Icon(imageVector = Icons.Filled.Check, contentDescription = "Check")
}
}
}
}
}

@Composable
fun recyclerView(tasks: MutableList<Task>) {
LazyColumn (modifier = Modifier.padding(vertical = 10.dp, horizontal = 80.dp)) {
items(items = tasks) {task ->
toDoItem(task.title, task.category, task)
}
}

}

最佳答案

您正在使用 MutableList<> ,不建议将其用于 Jetpack Compose 中的任何集合用例.我建议将其更改为 SnapshotStateList .

您的 recyclerView 可组合项看起来像这样

@Composable
fun recyclerView(tasks: SnapshotStateList<Task>) { ... }

在你设置东西的地方(例如 ViewModel )就像

tasks = mutableStateListOf<Task>( ... )

使用 SnapshotStateList将保证“更新”或re-composition使用您对它执行的任何正常列表操作,例如,

  • list.add( <new task> )
  • list.remove( <selected task> )
  • list[index] = task.copy() <- 更新列表的惯用方式

还有SnapshotStateMap这是Map key~value对用例。

但是如果您对如何更新 LazyColumn 感到好奇用普通的List ,您将不得不重新创建整个 MutableList<Task>这样它将通知 Composer 进行了更新,因为 MutableList<Task>现在指的是任务集合的新引用。

关于android - Jetpack 撰写 : LazyColumn not updating with MutableList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74134219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com