How to animate item visibility only once with Jetpack Compose and AnimatedVisibility?

1.5k Views Asked by At

So when I add

val state = remember {
    MutableTransitionState(false)
}
state.targetState = true
AnimatedVisibility(
    visibleState = state,
    enter = slideInHorizontally(
        animationSpec = tween(
            durationMillis = 250,
            delayMillis = animationDelay
        ),
        initialOffsetX = {
            screenWidthPx
        }
    )
) {
    content()
}

the animation is being triggered all the time when I return to this screen from another (popBackStack/naivateUp) or during config changes.

How to animate it only once?

1

There are 1 best solutions below

0
On BEST ANSWER

You are setting target state to true explicitly every time outside remember scope, now the target state would also be remembered and it wont animate unless you set target state to false

val state = remember {
    MutableTransitionState(false).apply {
      targetState = true
    }
}
AnimatedVisibility(
    visibleState = state,
    enter = slideInHorizontally(
        animationSpec = tween(
            durationMillis = 250,
            delayMillis = animationDelay
        ),
        initialOffsetX = {
            screenWidthPx
        }
    )
) {
    content()
}