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

Viewed 2411

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? :)

2 Answers

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

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

I found a very important parameter visibilityThreshold in the animateFloatAsState, you have to set it to 0.001f to make it work.

Related