Jetpack compose Animation handling when new items are created

71 Views Asked by At

I have the following code where I pass a list of colour balls, and each ball is animated based on enabled status. Now, the issue is when I again invoke the same function with a new list of balls, the y-axis value is the same as the previous list of values, and post animation is completed, which means new items are also shown at the bottom of the screen.

@Composable
fun MultipleBalls(
    enabled: Boolean = false,
    onSizeAvailable: ((maxWidth: Int, maxHeight: Int) -> Unit)? = null,
    generatedBalls: List<ColorBall>
) {
    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
        onSizeAvailable?.invoke(constraints.maxWidth, constraints.maxHeight)
        generatedBalls.forEach {
            CircleBox(ball = it, constraints.maxHeight, enabled)
        }
    }
}

@Composable
fun CircleBox(ball: ColorBall, maxHeight: Int, enabled: Boolean) {
    BoxWithConstraints {
        val animatedOffset: Float by animateFloatAsState(
            if (enabled) {
                maxHeight.toFloat() + ball.radius
            } else {
                ball.offset.y
            },
            animationSpec = snap(ball.animateTime),
            label = "animate_offset",
        )
        Canvas(
            modifier = Modifier
                .wrapContentSize()
        ) {
            drawCircle(
                color = ball.ballColor,
                radius = ball.radius,
                center = if (enabled) ball.offset.copy(y = animatedOffset) else ball.offset,
            )
        }
    }
}

What should I do so that when the new list is passed, each ball starts from the initial value and animates to the screen end?

Following is the color ball class.

data class ColorBall(
    val radius: Float,
    val offset: Offset,
    val ballJustClicked: Boolean,
    val ballColor: Color,
    val animateTime: Int,
) 
0

There are 0 best solutions below