In my OpinionViewModel:
val labels = MutableStateFlow<MutableList<String>>(mutableListOf())
when actions come from UI (from BottomSheet item) I add item to my list:
state.labels.value.add("Lorem Ipsu")
My main @Composable:
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()
}
}
})
}
}
}
@Composable Section:
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)
}
}
The problem is the no recomposition happening. I need to go back and open UI again to see added item. Am I missing something or the problem is related to bottom sheet?
CodePudding user response:
The problem is that your MutableList does not change when you modify its contents (the reference still remains the same). To fix this, use a List instead of MutableList.
val labels = MutableStateFlow(listOf<String>())
To add an element to it:
label.value = "Lorem Ipsum"
Now the state flow will emit a new value and your UI will get updated.