Jetpack 组合 uiState 中的更改不会触发重组

问题描述 投票:0回答:1

我想我还没有完全理解组合状态是如何工作的。当 uiState 中的项目发生更改时,我无法触发重组。

我正在构建一个需要通知访问的应用程序,因此我将用户导航到设置,并且在用户授予权限后,他们必须导航回该应用程序。这就是我想触发重组的地方。

我在 onResume 工作中进行了权限检查,并且 uiState 中的变量发生了变化,但没有调用重组。我在这里缺少什么?

可组合

@Composable
private fun MainLayout(viewModel: SetupViewModel){
    val uiState = viewModel.uiState.collectAsState()
    SetupItem(
        title = "Notification access",
        summary = if(uiState.value.hasNotificationPermission) stringResource(R.string.granted) else stringResource(R.string.not_granted){}
}

SetupUiState.kt

data class SetupUiState(
    var hasNotificationPermission: Boolean = false
)

我知道

hasNotificationPermission
设置为 true,但 SetupItem 中的摘要不会更新。我怎样才能做到这一点?

android android-jetpack-compose state android-jetpack
1个回答
10
投票

这里的问题是

hasNotificationPermission
字段是可变的(
var
而不是
val
)。 Compose 不跟踪内部字段的更改。您在这里有两个选择:

  1. 整体修改SetupUiState,假设您在ViewModel中使用StateFlow,它可以如下所示:
    fun setHasNotificationPermission(value: Boolean) {
        uiState.update { it.copy(hasNotificationPermission = value) }
    }
    
    您还应该将
    hasNotificationPermission
    从 var 更改为 val。
  2. 您可以利用 compose 的
    State
    并执行以下操作:
    class SetupUiState(
        initialHasPermission: Boolean = false
    ) {
        var hasNotificationPermission: Boolean by mutableStateOf(initialHasPermission)
    }
    
    有了这个,您就可以简单地执行
    uiState.hasNotificationPermission = value
    ,并且合成将会收到通知,因为它会自动跟踪
    State
    实例。
© www.soinside.com 2019 - 2024. All rights reserved.