android - 如何使用 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)
}
}
}
}
}
解决方案
在 compose 中你永远不想使用没有 的局部变量remember
,这不会在重组后保存它的状态
您可以通过三种方式声明它:
- 通过同时拥有 setter 和 getter,就像你所做的那样
showDialog
val (value, setValue) = remember { mutableStateOf("") }
- 通过拥有单身
MutableState
val
// declare
val setDialogTitle = remember { mutableStateOf("") }
// read/write
setDialogTitle.value = "new value"
- 使用委托属性。我觉得它最干净的一个:
// declare
var setDialogTitle by remember { mutableStateOf("") }
// read/write
setDialogTitle = "new value"
在文档中查看更多信息
推荐阅读
- django - 为什么当我使用 PasswordChangeForm 时 is_valid 返回 None?我完全确定我输入的凭据是正确的
- wordpress - 用于两个不同域的 WordPress 中的 Google 跟踪代码管理器
- postgresql - "\pset numericlocale" 没有在 postgres 中选择集合 lc_numeric
- r - 如何使用 proj4string 将数据框转换为同名的 SpatialPointsDataFrame?
- node.js - 有没有办法让不和谐的机器人从其他应用程序执行操作
- android - dnsmasq 正在使用更多 CPU
- owasp - ZAP 被动扫描规则是扫描的一部分,即使在禁用它们之后也是如此
- javascript - 将文本拆分为单词,忽略 JavaScript 中文本中的单引号单词
- unity3d - 在 Unity 3D 中拾取时如何使用相机移动游戏对象?
- node.js - 您可以使用 Angular Universal SSR 从 Docker 容器内部使用环境变量吗?