I want to show text with numbers and I wanted to achieve is to animate that text while displaying it. The animation is it should increase the counter from zero to the target value number. I tried using animateIntAsState but it's not working.
This is the state I tired :
val daysCounter by animateIntAsState(
targetValue = days ,
animationSpec = tween(
durationMillis = 5000,
easing = FastOutSlowInEasing
)
)
And text :
Text(
text = "$daysCounter",
fontSize = 40.sp,
color = MaterialTheme.colors.onPrimary,
fontWeight = FontWeight.Bold
)
From animateIntAsState
:
When the provided
targetValue
is changed, the animation will run automatically.
Your animation doesn't work because targetValue
is static.
The first recomposition must be done with an initial value, and the next recomposition you can pass the target value. For example, you can use LaunchedEffect
if you need to start the animation instantly(or with some delay) when the screen appears:
var days by remember { mutableStateOf(0) }
val daysCounter by animateIntAsState(
targetValue = days,
animationSpec = tween(
durationMillis = 5000,
easing = FastOutSlowInEasing
)
)
LaunchedEffect(Unit) {
days = 300
}
More info about animations in Compose can be found in documentation.