skip to content

In Compose, how does AnimatedVisibility slide an order summary in and out, and why does a plain if-statement not animate its removal?

level: juniorimportance: must knowfreq 74%

answer

  1. a Boolean drives appear and disappear
  2. EnterTransition and ExitTransition combined with +
  3. content stays composed until exit ends
  4. an if removes the content immediately
  5. MutableTransitionState animates the first appearance

basics

~20 s

AnimatedVisibility runs an EnterTransition when visible becomes true and an ExitTransition when it becomes false, keeping the content composed until the exit finishes. An if-statement removes the content at once, so there is nothing left to animate.

solid answer

~40 s

Wrap the order summary in `AnimatedVisibility(visible = showSummary, enter = ..., exit = ...)`. Enter transitions such as `slideInVertically`, `fadeIn`, `expandVertically` and `scaleIn` combine with `+` and run **simultaneously**; exits mirror them (`slideOutVertically`, `fadeOut`, `shrinkVertically`). Without arguments you get `fadeIn() + expandIn()` and `shrinkOut() + fadeOut()`, or vertical and horizontal variants inside a `Column` or `Row`. When `visible` turns false, `AnimatedVisibility` keeps the content in composition while the exit plays and only then removes and disposes it. With `if (showSummary) Summary()`, the composable leaves composition on the very next recomposition, so no exit can run. A first composition with `visible = true` shows the content without an enter animation; the `MutableTransitionState` overload animates that first appearance and lets you watch `isIdle` and `currentState`.

code

kotlin · 11 lines
kotlin
@Composable
fun OrderSummary(visible: Boolean, total: String) {
    AnimatedVisibility(
        visible = visible,
        enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(),
        exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut(),
        label = "orderSummary",
    ) {
        Text("Order total: $total")
    }
}

go deeper

for a junior

Recall the parameters, visible, enter and exit, the transition families, and that + combines them to run together.

for a middle

Explain why the content stays composed until the exit finishes, how the Column and Row defaults differ, and why the first composition does not animate.

for a senior

Show how MutableTransitionState lets you sequence work after an exit, and why custom exit values must use the scope's transition to avoid being cut off.

for a principal

Treat visibility animation as part of a component's contract. Shared panels should expose visible and transition parameters, not hard-code an if-statement that callers cannot animate.

## What AnimatedVisibility does **`AnimatedVisibility`** is the Compose composable for animating content **appearing and disappearing**. You give it a `visible: Boolean`, an **`EnterTransition`** for appearing and an **`ExitTransition`** for disappearing. When `visible` changes, it runs the matching transition on its content. For a flower-shop checkout, the order summary panel slides up from the bottom when the customer taps "Review order" and slides back down when they dismiss it: - `enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn()` - `exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut()` The lambdas receive the content's full height, so the panel starts and ends exactly one panel-height below its resting place. If you leave them out, `slideInVertically` starts from `-fullHeight / 2`, that is, from above. ## The transitions available There are four families of enter and exit transition. The KDoc names them: fade, expand and shrink, scale, and slide. | Effect | Enter | Exit | |---|---|---| | Fade | `fadeIn(initialAlpha)` | `fadeOut(targetAlpha)` | | Slide | `slideIn`, `slideInHorizontally`, `slideInVertically` | `slideOut`, `slideOutHorizontally`, `slideOutVertically` | | Scale | `scaleIn(initialScale)` | `scaleOut(targetScale)` | | Expand and shrink | `expandIn`, `expandHorizontally`, `expandVertically` | `shrinkOut`, `shrinkHorizontally`, `shrinkVertically` | Transitions combine with **`+`**. The KDoc is explicit that **the order of the combination does not matter**, because all the parts start at the same time. Each part takes its own `animationSpec`; the default for these is a spring with `Spring.StiffnessMediumLow`. Expand and shrink change the **layout size**, so siblings below the panel move with it, while slide and fade only move or fade the pixels. ## Defaults depend on where you call it - Top-level `AnimatedVisibility`: `fadeIn() + expandIn()` to enter, `shrinkOut() + fadeOut()` to exit. - Inside a `Column` (the `ColumnScope` overload): `fadeIn() + expandVertically()` and `fadeOut() + shrinkVertically()`. - Inside a `Row` (the `RowScope` overload): the horizontal equivalents. ## Why an if-statement cannot animate removal With `if (showSummary) OrderSummary()`, Compose removes `OrderSummary` from composition on the first recomposition after `showSummary` becomes false. Its nodes are gone, so there is nothing left to draw an exit animation on. `AnimatedVisibility` solves this by **keeping its content in composition while the exit transition runs**. Its KDoc says the content is removed and disposed only after all exit animations, built-in and custom, have finished. Appearing works the other way round: the content is composed first and then animated in. ## Lifecycle details that catch people 1. **First composition does not animate.** If `visible` is already true the first time `AnimatedVisibility` is composed, the content just appears. To animate on entry, use the overload that takes `visibleState: MutableTransitionState<Boolean>`, created with `MutableTransitionState(false)` and then given `targetState = true`. 2. **Observing progress.** That same `MutableTransitionState` tells you where the animation is: `isIdle` together with `currentState` distinguishes visible, appearing, disappearing and gone. This is how you run a follow-up action, such as clearing the summary's data, only after the panel has fully left. 3. **Child-specific motion.** Inside the content, `Modifier.animateEnterExit(enter, exit)` gives an individual child its own transition on top of the parent's. Pass `EnterTransition.None` and `ExitTransition.None` to the parent if only the children should move. 4. **Custom values must join the transition.** The content's `AnimatedVisibilityScope` exposes `transition`, a `Transition<EnterExitState>`. A colour animated with `transition.animateColor { ... }` is tracked, and `AnimatedVisibility` waits for it. A value animated with `animateFloatAsState` is not tracked, so the content can be removed before it finishes. ## Layout and sizing `AnimatedVisibility` wraps its content in its own layout. The KDoc says that layout takes the largest width and height of its children and aligns them all to the top start. The `modifier` parameter applies to that wrapper, not directly to the content, and the wrapper itself leaves the tree with the content once the exit finishes, so padding placed there takes no space while the panel is hidden. When the panel uses an expand or shrink transition, that wrapper's size animates, which is how the content below the order summary moves smoothly up and down. With slide and fade alone, the wrapper keeps its full size for the whole exit and then disappears in one step, so siblings jump at the end. If the space should close smoothly, add `shrinkVertically()` to the exit. ## When to reach for something else - To **swap one piece of content for another** (one price for a new one), use `AnimatedContent`. - To animate a composable that stays on screen but **changes size**, use `Modifier.animateContentSize()`. - To animate list items being added, removed or reordered in a lazy list, see the lazy-list material. That belongs to the lists API, not to `AnimatedVisibility`.

  • How do you clear the order data only after the summary has finished sliding out?
    Use the `AnimatedVisibility` overload that takes a `MutableTransitionState<Boolean>`. Set its `targetState = false` to hide the panel, then act once `isIdle` is true and `currentState` is false. That means the exit transition has fully finished and the content has been removed.
  • The summary's inner total line should slide while the panel only fades; how?
    Give the panel `fadeIn()`/`fadeOut()` and put `Modifier.animateEnterExit(enter = slideInVertically(), exit = slideOutVertically())` on the total line inside the content. The child's effect combines with the parent's. Pass `EnterTransition.None` and `ExitTransition.None` to the parent if only the children should animate.

  • An if-statement around the composable is enough to animate its removal.
  • Transitions joined with + run one after another in written order.
  • AnimatedVisibility keeps hidden content composed with zero alpha.
  • Content shown with visible = true on first composition plays its enter animation.
  • An animateFloatAsState exit inside the content is always waited for.