在我的OpinionViewModel:中
val labels = MutableStateFlow<MutableList<String>>(mutableListOf())
当操作来自UI(来自BottomSheet项目(时,我将项目添加到我的列表中:
state.labels.value.add("Lorem Ipsu")
我的主@可组合:
fun OpinionScreen(viewModel: OpinionViewModel) {
val scrollState = rememberScrollState()
val bottomState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
val items by viewModel.state.labels.collectAsState()
AppTheme(isSystemInDarkTheme()) {
ModalBottomSheetLayout(
sheetState = bottomState,
sheetContent = { AddPhotoBottomSheet()}) {
Scaffold(
topBar = { TopBar()},
content = {
Box(
modifier = Modifier.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.verticalScroll(scrollState)
) {
FirstSection()
HowLongUsageSection(photos)
ThirdSection()
}
}
})
}
}
}
@可组合部分:
fun HowLongUsageSection(labels: MutableList<String>) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp, start = 10.dp, end = 10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
labels.forEach {
Text(text = it, color = Color.Blue)
}
}
问题是没有重组发生。我需要返回并再次打开UI以查看添加的项目。是我遗漏了什么,还是问题与底页有关?
问题是,当您修改MutableList的内容时,它不会改变(引用仍然保持不变(。若要解决此问题,请使用列表而不是MutableList。
val labels = MutableStateFlow(listOf<String>())
添加元素:
label.value += "Lorem Ipsum"
现在,状态流将发出一个新值,并且您的UI将得到更新。