In Compose, how do animateDpAsState and animateColorAsState animate a bouquet price badge, and what happens when the target changes mid-animation?
answer
- pass a target, read a State
- remembered Animatable at the call site
- first target is the starting value
- retarget keeps current value and velocity
- default spec is spring(), not a tween
basics
~20 sanimateDpAsState and animateColorAsState take a target value and return a State that moves toward it each frame under a spring by default. A new target mid-flight redirects the running animation from its current value and velocity.
solid answer
~40 s`animateDpAsState(targetValue)` and `animateColorAsState(targetValue)` are fire-and-forget: you compute the target from state (say, the selected bouquet size) and read the returned `State` with `by`. An `Animatable` is created and remembered at the call site with the first target as its starting value, so nothing animates on first composition. Each later target starts an animation; if one is already running it adjusts course from its current value **and velocity**. With no `animationSpec` they use `spring()` (`Spring.DampingRatioNoBouncy`, `Spring.StiffnessMedium`), which keeps velocity continuous on interruption; pass `tween(...)` or `keyframes { }` for timed motion. You cannot stop or cancel them except by removing the call from composition. Need that control? Use `Animatable` directly.
code
kotlin · 16 lines@Composable
fun PriceBadge(size: BouquetSize, price: String) {
val large = size == BouquetSize.Large
val badgeWidth by animateDpAsState(
targetValue = if (large) 96.dp else 64.dp,
label = "badgeWidth",
)
val badgeColor by animateColorAsState(
targetValue = if (large) Color.Magenta else Color.LightGray,
animationSpec = tween(durationMillis = 250),
label = "badgeColor",
)
Box(Modifier.width(badgeWidth).background(badgeColor)) {
Text(price)
}
}go deeper
Recall the shape: pass a target, get a State back, read it with by. Name the default spring and show how to pass a tween instead.
Explain the remembered Animatable behind each call, why the first composition does not animate, and how a new target redirects from the current value and velocity.
Show where animate*AsState stops being enough: no stop or cancel, finishedListener skipped for interrupted runs, and values that must stay in lockstep. Move those cases to Animatable or updateTransition.
Weigh the simplest API against control. A team rule might default to animate*AsState with spring specs for state-driven UI, and allow Animatable only where gestures or cancellation need it.
## What the animate*AsState family is The **animate*AsState** functions are the simplest animation APIs in Compose. Each one animates a **single value** of one type: `animateFloatAsState`, `animateDpAsState`, `animateColorAsState`, `animateIntAsState`, `animateOffsetAsState`, `animateSizeAsState`, `animateRectAsState`, `animateIntOffsetAsState` and `animateIntSizeAsState`. For any other type, `animateValueAsState` takes a `TwoWayConverter` that maps your type to an `AnimationVector` and back. You give the function a **target value**, usually an expression over state such as `if (size == BouquetSize.Large) 96.dp else 64.dp`. It returns a `State<T>`. Reading that state with `by` gives you the animated value. While an animation runs, the value changes every frame, and whatever reads it (a composable, or a layout or draw lambda) is updated. ## What happens under the hood The Android documentation describes the mechanism plainly: an **`Animatable`** is created and remembered at the call site, with the **first target value as its initial value**. Three behaviours follow from that: - **No animation on first composition.** The badge appears at its first target. To animate in on first display, use `Animatable` with an initial value different from the first target, or a transition started from a `MutableTransitionState`. - **Every new target starts an animation.** When recomposition passes a different target, an animation toward it starts automatically. - **Interruption is handled for you.** If an animation is already in flight, it is redirected: the new animation starts from the **current value and velocity**, not from the old start or the old target. ## The default spec, and when to change it With no `animationSpec`, these functions use a **spring**. For `animateFloatAsState` the default is a `spring()` with a 0.01 visibility threshold; for `animateDpAsState` it is `spring(visibilityThreshold = Dp.VisibilityThreshold)`. The **visibility threshold** is the distance from the target at which the animation counts as finished, so a spring does not keep settling invisibly for many frames. The spring defaults are `dampingRatio = Spring.DampingRatioNoBouncy` (1f) and `stiffness = Spring.StiffnessMedium` (1500f). | Spec | How you write it | What it gives you | |---|---|---| | `spring` | `spring(dampingRatio, stiffness)` | physics motion, no fixed duration, velocity carried across interruptions | | `tween` | `tween(durationMillis = 300, delayMillis = 0, easing = FastOutSlowInEasing)` (the defaults) | a fixed duration along an easing curve | | `keyframes` | `keyframes { durationMillis = 375; 0.4f at 75 }` | values pinned at timestamps | | `snap` | `snap(delayMillis = 50)` | jumps to the target, optionally after a delay | The documentation says a spring handles interruptions more smoothly than a duration-based spec because it **guarantees continuity of velocity** when the target changes mid-animation. A `tween` restarts its full duration from wherever the value is, so a badge that is tapped repeatedly can look jerky. Choose a `tween` when the motion must take a fixed time, such as a colour fade timed to match another element. ## Applying it to the price badge For a bouquet-size selector, two values change together when the size changes: 1. The badge width: `animateDpAsState(targetValue = if (large) 96.dp else 64.dp, label = "badgeWidth")`. 2. The badge colour: `animateColorAsState(targetValue = ..., animationSpec = tween(250), label = "badgeColor")`. Each call animates on its own. If the two must stay in lockstep or share one notion of "done", a single `updateTransition` with child animations is the better fit. ## Limits worth knowing - **No stop or cancel.** The KDoc says it directly: these functions cannot be cancelled or stopped without removing the composable from the tree. For a stoppable or gesture-driven value, use `Animatable` with `stop()`, `snapTo()` and `animateTo()`. - **`finishedListener`** is called with the final value when an animation reaches its target. If a newer target interrupts an animation, the listener does not run for the interrupted one. It runs once the newer animation reaches its target. - **`label`** names the animation in Android Studio's animation tooling. Give each call a distinct label. - **Reading cost.** The animated state changes every frame. Reading it in a layout or draw lambda instead of in composition is a modifier technique covered with Compose modifiers, not here. - **Leaving composition ends it.** The animation belongs to the call site, so removing that composable stops the animation along with it. Once these points are clear, the API rarely surprises you: compute the target, read the state, let the spring absorb rapid changes, and switch to `Animatable` when you need imperative control.
- Why does the badge not animate the first time the screen appears, and how would you make it animate in?The remembered `Animatable` starts at the first target value, so the first composition just shows that value. To animate on first display, remember an `Animatable` with a different initial value and call `animateTo` in a `LaunchedEffect`, or drive the value from a transition started with a `MutableTransitionState` whose initial state differs from its target.
- A product owner wants a tap to freeze the badge mid-animation; can animateDpAsState do that?No. Its KDoc says it cannot be cancelled or stopped without removing the composable from the tree. Hold the value in a remembered `Animatable` instead: `stop()` halts it in place without jumping to the target, and `animateTo` resumes later from wherever it stopped.
- How do you animate a type with no built-in animate*AsState, such as a data class holding two Dp values?Use `animateValueAsState` with a `TwoWayConverter` that turns the value into an `AnimationVector2D` and back. Each dimension of the vector animates with its own velocity tracking, so both fields move smoothly and handle interruption the same way the built-in types do.
- animate*AsState animates from zero on the first composition.
- A new target waits for the running animation to finish first.
- The default animationSpec is a 300 ms tween.
- You can call stop() on the State that animateDpAsState returns.
- finishedListener fires for every interrupted animation as well.