值不更新(Jetpack Compose)

value not updating (Jetpack Compose)

我正在尝试根据自己的需要改编视频教程。基本上,我有一个盒子列表,我希望每个盒子都以 1 秒的延迟进行动画处理。我不明白为什么我的代码不起作用。

delay.value

似乎没有更新。有什么想法吗?

    @Composable
fun Rocket(
    isRocketEnabled: Boolean,
    maxWidth: Dp,
    maxHeight: Dp
) {
    val modifier: Modifier
    val delay = remember { mutableStateOf(0) }
    val tileSize = 50.dp
    if (!isRocketEnabled) {
        Modifier.offset(
            y = maxHeight - tileSize,
        )
    } else {
        val infiniteTransition = rememberInfiniteTransition()
        val positionState = infiniteTransition.animateFloat(
            initialValue = 0f,
            targetValue = 1f,
            animationSpec = infiniteRepeatable(
                animation = tween(
                    durationMillis = 2000,
                    delayMillis = delay.value,
                    easing = LinearEasing
                )
            )
        )
        modifier = Modifier.offset(
            x = (maxWidth - tileSize) * positionState.value,
            y = (maxHeight - tileSize) - (maxHeight - tileSize) * positionState.value,
        )
        listOf(
            Color(0xffDFFF00),
            Color(0xffFFBF00),
            Color(0xffFF7F50),
            Color(0xffDE3163),
            Color(0xff9FE2BF),
            Color(0xff40E0D0),
            Color(0xff6495ED),
            Color(0xffCCCCFF),
        ).forEachIndexed { index, color ->
            Box(
                modifier = modifier
                    .width(tileSize)
                    .height(tileSize)
                    .background(color = color)
            )
            delay.value += 1000
        }
    }
}

当可组合项中记住的状态发生更改时,整个可组合项将重新组合。

所以要达到给定的要求,

我们可以简单地使用 Int 延迟并在 forEach 循环中更新其值,并使用更新后的延迟创建动画,而不是将延迟用作 mutableState

.forEachIndexed { index, color ->
            Box(
                modifier = createModifier(maxWidth, maxHeight, tileSize, createAnim(delay = delay))
                    .width(tileSize)
                    .height(tileSize)
                    .background(color = color)
            )
            delay += 1000
        }

创建带有动画的修改器:-

fun createModifier(maxWidth: Dp, maxHeight: Dp, tileSize: Dp, positionState: State<Float>): Modifier {
    return  Modifier.offset(
        x = ((maxWidth - tileSize) * positionState.value),
        y = ((maxHeight - tileSize) - (maxHeight - tileSize) * positionState.value),
    )
}

@Composable
fun createAnim(delay: Int): State<Float> {
    val infiniteTransition = rememberInfiniteTransition()
    return infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 1f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 2000,
                delayMillis = delay,
                easing = LinearEasing
            )
        )
    )
}