Home > Blockchain >  Jetpack Compose animateFLoatAsState replaced by Transition.animateFloat is not working
Jetpack Compose animateFLoatAsState replaced by Transition.animateFloat is not working

Time:10-18

Could you tell me why it stops working when I use val animateAngle: Float by transition.animateFloat instead of val animateAngle by animateFloatAsState?

It seems that the variable rotated is not updated when the button is clicked.


    var rotated by remember {
        mutableStateOf(false)
    }

    val transition = updateTransition(
        targetState = rotated,
        label = "Rotate"
    )

        val animateAngle: Float by transition.animateFloat(
            transitionSpec = {
                tween(2000)
            },
            label = "Rotate box"
        ) { state ->
            when(state){
                rotated -> 360f
                else -> 0f
            }

        }

        Column (
        ) {
            Image(
                painter = painterResource(id = R.drawable.propeller),
                contentDescription = "fan",
                modifier = Modifier
                    .rotate(animateAngle)
                    .padding(30.dp)
                    .size(100.dp))

            Button(
                onClick = {
                    rotated = !rotated
                },
            ) {
                Text(text = "Rotate Box")
            }
        }

CodePudding user response:

You have a boolean mutableState that you use as a targetState for your transition, true or false will be its target state.

val transition = updateTransition(
    targetState = rotated,
    label = "Rotate"
)

Now you are reading that boolean mutableState inside targetValueByState lambda

when(state) {
    rotated -> 360f
    else -> 0f
}

and because you are reading it there, the animationAngle will always get a value of 360f, regardless if its true or false.

I logged it

Log.e("AnimatedAngle", "$animateAngle : Rotated boolean state [$rotated]")

and it prints:

360.0 : Rotated boolean state [false]
360.0 : Rotated boolean state [true]

Just simply remove it and slightly modify the targetValueByState block this way, and your animation will work.

val animateAngle: Float by transition.animateFloat(
      transitionSpec = {
          tween(2000)
      },
      label = "Rotate box"
) { state ->
      if (state) 360f else 0f
}
  • Related