title: How to animate elements of a dynamic list in Jetpack Compose?
body: <p>How can I transition elements of a list to the new list (possibly different size) with animation?</p>
  <p>I have a pie chart and when its slices (fractions) change, I want to animate the previous fractions to the new fractions. The thing is, number of slices can be different each time.</p>
  <p>If number of new slices is less than the current ones, the current extra slices should animate from their current fraction to <code>0</code>.<br />
  If number of new slices is greater than the current ones, new extra slices should animate from <code>0</code> to their fractions.</p>
  <pre class="lang-kotlin prettyprint-override"><code>@Composable fun PieChartCompose(slices: List&lt;Float&gt;) {
      val transitionData = updateTransitionData(slices)
      val fractions = transitionData.fractions
      // Draw the pie with Canvas using the fractions
  }
  </code></pre>
  <p>I have currently implemented this with a list of constant size (10, so slices cannot be more than 10)<br />
  (note that the initial animation for chart appearance can be different from subsequent animations):</p>
  <pre class="lang-kotlin prettyprint-override"><code>data class TransitionData(val slices: List&lt;State&lt;Float&gt;&gt;)
  
  enum class ChartState { INITIALIZED, CHANGED }
  
  @Composable fun updateTransitionData(
      targetFractions: List&lt;Float&gt;
  ): TransitionData {
      val mutableState = remember { MutableTransitionState(ChartState.INITIALIZED) }
      mutableState.targetState = ChartState.CHANGED
      val transition = updateTransition(mutableState, label = &quot;main-animation&quot;)
      
      val fractions = listOf(
          transition.animateFloat(label = &quot;fraction-0-animation&quot;) {
              if (it == ChartState.INITIALIZED) 0f
              else targetSlices.getOrNull(0)?.fraction ?: 0f
          },
          // ...
          transition.animateFloat(label = &quot;fraction-10-animation&quot;) {
              if (it == ChartState.INITIALIZED) 0f
              else targetSlices.getOrNull(10)?.fraction ?: 0f
          }
      )
      return remember(transition) { TransitionData(fractions) }
  }
  </code></pre>
  <p>Below is an example chart that initially has two slices and then animates to one slice<br />
  (the first slice animates to the single new fraction and the second slice animates to <code>0</code>—<br />
  they are a little inconsistent probably because of interpolations and animation specs):</p>
  <p><img src="https://i.stack.imgur.com/sYlBQ.gif" alt="Example desired animation" /></p>
  <pre class="lang-kotlin prettyprint-override"><code>var slices by mutableStateOf(listOf(0.3f, 0.7f))
  PieChartCompose(slices)
  slices = listOf(1f)
  </code></pre>