animateTo

Function

Common
public suspend fun <T, V : AnimationVector> AnimationState<T, V>.animateTo(
    targetValue: T,
    animationSpec: AnimationSpec<T> = spring(),
    sequentialAnimation: Boolean = false,
    block: AnimationScope<T, V>.() -> Unit = {},
)

Target based animation that takes the value and velocity from the AnimationState as the starting condition, and animate to the targetValue, using the animationSpec. During the animation, the given AnimationState will be updated with the up-to-date value/velocity, frame time, etc.

Parameters

targetValueThe target value that the animation will animate to.
animationSpecThe animation configuration that will be used. spring by default.
sequentialAnimationIndicates whether the animation should use the AnimationState.lastFrameTimeNanos as the starting time (if true), or start in a new frame. By default, sequentialAnimation is false, to start the animation in a few frame. In cases where an on-going animation is interrupted and a new animation is started to carry over the momentum, using the interruption time (captured in AnimationState.lastFrameTimeNanos) creates a smoother animation.
blockWill be invoked on every frame, and the AnimationScope will be checked against cancellation before the animation continues. To cancel the animation from the block, simply call AnimationScope.cancelAnimation. After AnimationScope.cancelAnimation is called, block will not be invoked again. The animation loop will exit after the block returns. All the animation related info can be accessed via AnimationScope.

Code Examples

animateToOnAnimationState

fun animateToOnAnimationState() {
    @Composable
    fun simpleAnimate(target: Float): Float {
        // Create an AnimationState to be updated by the animation.
        val animationState = remember { AnimationState(target) }
        // Launch the suspend animation into the composition's CoroutineContext, and pass
        // `target` to LaunchedEffect so that when`target` changes the old animation job is
        // canceled, and a new animation is created with a new target.
        LaunchedEffect(target) {
            // This starts an animation that updates the animationState on each frame
            animationState.animateTo(
                targetValue = target,
                // Use a low stiffness spring. This can be replaced with any type of `AnimationSpec`
                animationSpec = spring(stiffness = Spring.StiffnessLow),
                // If the previous animation was interrupted (i.e. not finished), configure the
                // animation as a sequential animation to continue from the time the animation was
                // interrupted.
                sequentialAnimation = !animationState.isFinished,
            )
            // When the function above returns, the animation has finished.
        }
        // Return the value updated by the animation.
        return animationState.value
    }
}