首页 > 解决方案 > 如何使用 Jetpack compose 更新变量 ~ Kotlin Coroutine

问题描述

/** 因为会有不止一个按钮可以打开对话窗口。例如,打开不同样式窗口的社交媒体按钮。电话号码,您可以在其中看到电话号码..等。因此,我希望只有一个函数具有有关对话框的所有详细信息,而不是每个按钮都会更新变量并将其传递给对话框函数。*/

@Composable
fun CardSell(modifier: Modifier = Modifier){

    val (showDialog, setShowDialog) = remember { mutableStateOf(false) }

    var setDialogTitle : String = "" //Update this variable

    val padding = 9.dp
    val scope = rememberCoroutineScope()

    Column(Modifier
        .clickable(onClick = {})) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Card(elevation = 4.dp) {
                Column {
                    Row(modifier = Modifier.padding(all = 8.dp)){
                        Image(
                            painter = painterResource(id = R.drawable.ic_launcher_foreground),
                            contentDescription = "Contact Profile Picture",
                            modifier = Modifier
                                .size(40.dp)
                                .clip(CircleShape)
                        )
                    }

                    Row(modifier = Modifier
                        .fillMaxWidth()
                        .padding(8.dp),
                            horizontalArrangement = Arrangement.SpaceEvenly){

                        IconButton(
                            onClick = {
                                setShowDialog(true)
                                scope.launch {
                                    setDialogTitle = "Phone Number: ${user.contact.phoneNumber}"
                                    delay(100)
                                }

                            },
                        ) { //Phone Icon
                            Icon(
                                Icons.Filled.Phone,
                                contentDescription = "Phone Number"
                            )
                        }

                        }
                    }
                    
                    DialogDemo(showDialog, setShowDialog, setDialogTitle)

                }
            }
        }
    }
}

标签: androidkotlinkotlin-coroutinesandroid-jetpack-compose

解决方案


在 compose 中你永远不想使用没有 的局部变量remember,这不会在重组后保存它的状态

您可以通过三种方式声明它:

  1. 通过同时拥有 setter 和 getter,就像你所做的那样showDialog
val (value, setValue) = remember { mutableStateOf("") }
  1. 通过拥有单身MutableState val
// declare
val setDialogTitle = remember { mutableStateOf("") }

// read/write
setDialogTitle.value = "new value"
  1. 使用委托属性。我觉得它最干净的一个:
// declare
var setDialogTitle by remember { mutableStateOf("") }

// read/write
setDialogTitle = "new value"

在文档中查看更多信息


推荐阅读