gpt4 book ai didi

android - mutableStateOf 在 View 模型中更新但在@Compose 中没有效果

转载 作者:行者123 更新时间:2023-12-05 05:52:53 25 4
gpt4 key购买 nike

我的 HiltViewModel 中确实有一个名为 loading 的 mutableStateof。我正在更新从 View 模型中的函数加载的值,该函数正在传递给@composable 函数并在那里使用。情况是加载值在 viewModel 中完美更新,但未反射(reflect)在 @Composable 函数中。我的 View 模型是:

@HiltViewModel
class AuthenticationViewModel @Inject constructor(
private val repository: AppRepository,
application: Application
): ViewModel() {
val loading = mutableStateOf(false)

fun update() = viewModelScope.launch {
loading.value = true
}
}

加载值在此处更新但未反射(reflect)在@composable 中

@Composable
fun LoginScreen(
viewModel: AuthenticationViewModel,
actions: MainActions
) {
val loading = viewModel.loading.value

//Loading is another composable function where bool value is passed
Loading(state = loading)
CustomNavigationButton(title = "Sign In",enabled = true,onClick =
{viewModel.update()})
}

现在当我点击导航按钮时, View 模型函数被调用并且加载状态也被更新但没有反射(reflect)回@Composable

加载可组合项是:

@Composable
fun Loading(state:Boolean) {
var showDialog by remember { mutableStateOf(state) }

if(showDialog){
Dialog(onDismissRequest = { showDialog = false }, DialogProperties(
dismissOnBackPress = false,dismissOnClickOutside = false
)) {
Box(
modifier = Modifier.size(100.dp).background(Color.White, shape = RoundedCornerShape(8.dp)),
contentAlignment= Alignment.Center,
){
CircularProgressIndicator()
}
}
}
}

最佳答案

问题出在 Loader 可组合函数中。 if condition 始终设置为 false,因为可变状态从未在该特定可组合函数中更新。替换:

@Composable
fun Loading(state:Boolean) {
var showDialog by remember { mutableStateOf(state) }

if(showDialog){
Dialog(onDismissRequest = { showDialog = false }, DialogProperties(
dismissOnBackPress = false,dismissOnClickOutside = false
)) {
Box(
modifier = Modifier.size(100.dp).background(Color.White, shape = RoundedCornerShape(8.dp)),
contentAlignment= Alignment.Center,
){
CircularProgressIndicator()
}
}
}
}

@Composable
fun Loading(state:Boolean) {
if(state){
Dialog(onDismissRequest = {}, DialogProperties(
dismissOnBackPress = false,dismissOnClickOutside = false
)) {
Box(
modifier = Modifier.size(100.dp).background(Color.White, shape = RoundedCornerShape(8.dp)),
contentAlignment= Alignment.Center,
){
CircularProgressIndicator()
}
}
}
}

关于android - mutableStateOf 在 View 模型中更新但在@Compose 中没有效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70024264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com