jetpack compose 中可变列表无法实时更新的问题


        var courses by rememberSaveable { mutableStateOf(mutableListOf<String>()) }
        val physiotherapy = stringResource(R.string.physiotherapy)
        val chemotherapy = stringResource(R.string.chemotherapy)
        val biology = stringResource(R.string.biology)
        val political = stringResource(R.string.political)
        val history = stringResource(R.string.history)
        val geography = stringResource(R.string.geography)
        val courseList = listOf(physiotherapy, chemotherapy, biology, political, history, geography)

                    courseList.forEachIndexed { _, s ->
                        FilterChip(
                            selected = s in courses,
                            leadingIcon = {
                                AnimatedVisibility(visible = s in courses) {
                                    Icon(
                                        imageVector = Icons.Rounded.Done,
                                        contentDescription = stringResource(R.string.selected)
                                    )
                                }
                            },
                            onClick = {
                                courses.apply {
                                    if (s in this) {
                                        remove(s)
                                    } else {
                                        add(s)
                                    }
                                }
                            },
                            label = { Text(text = s) }
                        )
                    }

这是我使用 Jetpack Compose 所写的一段代码,这段代码在一个弹窗里,就是一个高中生选科的功能,但是 FilterChip 被点击后,不会实时更新,只有在再次打开弹窗后才会生效,求解

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 以下回答由chatgpt基于相关博客总结生成:

    这个问题可以通过使用remembermutableStateListOf解决。下面是具体的解决方案:

    1. 首先,确保你已经在项目中引入了androidx.compose.runtimeandroidx.compose.runtime.livedata依赖。

    2. 使用remember来保存选科的状态,该状态将在组合函数重新计算时保持不变。例如,你可以在调用函数中使用remember来保存一个mutableStateListOf

    kotlin val selectedSubjects = remember { mutableStateListOf<String>() }

    1. 在 FilterChip 的点击处理函数中,更新选科的列表。给 FilterChip 添加一个点击监听器,并在监听器中更新选科列表。以下是一个示例:

    kotlin FilterChip( label = { Text(subject) }, selected = selectedSubjects.contains(subject), onSelectedChange = { isSelected -> if (isSelected) { selectedSubjects.add(subject) } else { selectedSubjects.remove(subject) } } )

    当点击 FilterChip 时,会根据是否已选中来添加或删除相应的科目。

    1. 使用选科列表来更新你的弹窗内容。你可以在弹窗内容中使用选科列表进行筛选或展示。例如,你可以使用selectedSubjects列表过滤你的数据,并在弹窗内容中更新。

    ```kotlin val filteredData = data.filter { item -> selectedSubjects.any { it == item.subject } }

    // 在弹窗中使用 filteredData ```

    这样,当你点击 FilterChip 时,选科结果将实时更新。确保在弹窗中使用filteredData来展示经过筛选的数据。

    希望以上解决方案对你有帮助。如果你还有其他问题,请随时提问。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^