如何将 AnimatedVisibility 与可为 null 的值一起使用?

zol*_*ish 4 android-jetpack-compose

我发现自己经常处于这种情况。我有一些值,如plates下面的示例所示,我想根据其是否为空来显示/隐藏它。但隐藏它总是会失败,因为只要它为空,就不会渲染任何内容,并且动画只是捕捉到空的虚无。

我怎样才能做到这一点?我想一直呆plates到动画结束。

    AnimatedVisibility(
        visible = plates != null,
        content = {
            if (plates != null) {
                // Render plates
            } else {
                // The animation snaps to nothingness, as opposed to animating out
            }
        })
Run Code Online (Sandbox Code Playgroud)

zol*_*ish 6

这就是我最终所做的,并且它按预期工作!

@Composable
inline fun <T> AnimatedValueVisibility(
    value: T?,
    enter: EnterTransition = fadeIn(
        animationSpec = FloatSpec
    ) + expandVertically(
        animationSpec = SizeSpec,
        clip = false
    ),
    exit: ExitTransition = fadeOut(
        animationSpec = FloatSpec
    ) + shrinkVertically(
        animationSpec = SizeSpec,
        clip = false
    ),
    crossinline content: @Composable (T) -> Unit
) {
    val ref = remember {
        Ref<T>()
    }

    ref.value = value ?: ref.value

    AnimatedVisibility(
        visible = value != null,
        enter = enter,
        exit = exit,
        content = {
            ref.value?.let { value ->
                content(value)
            }
        }
    )
}
Run Code Online (Sandbox Code Playgroud)