Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AnimatedVisibility with nullable values?

I find myself in this situation quite often. I have some value like plates in the sample below, and I want to show/hide it depending on if its null or not. But hiding it always fails since nothing is rendered whenever its null, and the animation just snaps to empty nothingness.

How can I make this work? Id like to keep plates around until the animation finishes.

    AnimatedVisibility(
        visible = plates != null,
        content = {
            if (plates != null) {
                // Render plates
            } else {
                // The animation snaps to nothingness, as opposed to animating out
            }
        })
like image 628
zoltish Avatar asked Feb 24 '26 15:02

zoltish


1 Answers

This is what I ended up doing, and it works as expected!

@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)
            }
        }
    )
}
like image 183
zoltish Avatar answered Feb 26 '26 06:02

zoltish