【问题标题】:How to Updating a variable using Jetpack compose ~ Kotlin Coroutine如何使用 Jetpack compose 更新变量 ~ Kotlin Coroutine
【发布时间】:2021-10-15 05:12:36
【问题描述】:

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

@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)

                }
            }
        }
    }
}

【问题讨论】:

  • 您希望从哪里修改setDialogTitle 变量?我假设您希望将它传递给DialogDemo,但是从哪里修改它呢?精心制作

标签: android kotlin kotlin-coroutines android-jetpack-compose


【解决方案1】:

在 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"

documentation 中查看更多信息

【讨论】:

  • 非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
相关资源
最近更新 更多