简体   繁体   English

无需重新组合 [Jetpack Compose]

[英]No recomposition [Jetpack Compose]

In my OpinionViewModel:在我的 OpinionViewModel 中:

val labels = MutableStateFlow<MutableList<String>>(mutableListOf())

when actions come from UI (from BottomSheet item) I add item to my list:当操作来自 UI(来自BottomSheet 项目)时,我将项目添加到我的列表中:

 state.labels.value.add("Lorem Ipsu") 

My main @Composable:我的主要@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.我需要返回并再次打开 UI 以查看添加的项目。 Am I missing something or the problem is related to bottom sheet?我是否遗漏了什么或问题与底页有关?

The problem is that your MutableList does not change when you modify its contents (the reference still remains the same).问题是当你修改它的内容时你的 MutableList 不会改变(引用仍然保持不变)。 To fix this, use a List instead of MutableList.要解决此问题,请使用 List 而不是 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.现在状态流将发出一个新值,您的 UI 将得到更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM