Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate the progress of a LinearProgressIndicator in Jetpack Compose?

I have a LinearProgressIndicator that correctly shows the current progress. Now I would like the progress to be animated and I thought this would be super simple with animateFloatAsState. Well, not sure what I am not grokking, but with the code below, the progress is not animated, but immediately shown at the correct place.

@Composable
fun MyIndicator() {
    val progressAnimDuration = 1500
    val progressAnimation by animateFloatAsState(
        targetValue = 0.35f
        animationSpec = tween(durationMillis = progressAnimDuration, easing = FastOutSlowInEasing)
    )
     LinearProgressIndicator(
        progress = progressAnimation,
        ...
        modifier = Modifier           
           .fillMaxWidth()
           .clip(RoundedCornerShape(20.dp)). // Rounded edges
    )
}

So whenever I show that component on the screen, I would expect the progress to be animated to its correct progress state. But instead, the progress is not animated but immediately shown at the correct progress state.

What's wrong here? :)

like image 977
Johan Paul Avatar asked Dec 03 '25 09:12

Johan Paul


1 Answers

I had a similar problem, in my case I used LaunchedEffect to update the progress from zero to the desired value

@Composable
fun AnimatedLinearProgressIndicator(
    indicatorProgress: Float,
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
) {
    var progress by remember { mutableStateOf(0F) }
    val progressAnimDuration = 1_500
    val progressAnimation by animateFloatAsState(
        targetValue = progress,
        animationSpec = tween(durationMillis = progressAnimDuration, easing = FastOutSlowInEasing),
    )
    LinearProgressIndicator(
        progress = { progressAnimation },
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp)),
    )
    LaunchedEffect(lifecycleOwner) {
        progress = indicatorProgress
    }
}
like image 154
Dani Chuks Avatar answered Dec 04 '25 23:12

Dani Chuks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!