animate*AsState Basics
Smoothly animate single values.
Animate a Single Value
The simplest way to animate in Compose is the animate*AsState family. You give it a target value, and it returns a State that smoothly animates from the current value to the target whenever the target changes.
There's a variant for each common type: animateFloatAsState, animateDpAsState, animateColorAsState, animateOffsetAsState, and more.
animateFloatAsState
animateFloatAsState animates a single Float. A common use is opacity (alpha). When visible flips, the returned alpha glides between 0f and 1f.
Note the by keyword: it lets you read the animated State<Float> directly as a plain Float.
@Composable
fun FadingLabel(visible: Boolean) {
val alpha by animateFloatAsState(
targetValue = if (visible) 1f else 0f,
label = "alpha"
)
Text(
"Hello",
modifier = Modifier.graphicsLayer { this.alpha = alpha }
)
}All lessons in this course
- Why Animations Matter
- animate*AsState Basics
- AnimatedVisibility and Transitions
- Gesture and Spring Animations