🐕

Compose Animation when a list item added / deleted

2023/09/12に公開

Define temporary animations add and delete from a list until the animations are implemented from the official.

Repository

data class Item(
    val id: Int,
    val description: String,
)
@Composable
fun AnimationListItem(
    item: Item,
    duration: Int
) {
    val itemVisibility = remember { Animatable(0f) }
    val scope = rememberCoroutineScope()
    var initialLoad by rememberSaveable { mutableStateOf(true) }
    LaunchedEffect(key1 = item.id) {
        if (initialLoad) {
            itemVisibility.animateTo(targetValue = 1f, animationSpec = tween(duration))
            initialLoad = false
        } else {
            itemVisibility.snapTo(1f)
        }
    }
    // Card, Button etc...
    SomethingComposable(
        modifier = Modifier.alpha(itemVisibility.value),
        onClick = {
            scope.launch {
                itemVisibility.animateTo(targetValue = 0f, animationSpec = tween(duration))
                deleteItem(item.id)
            }
        }
    ) {
	Text(item.description)
    }
}
@Composable
fun Example(
    itemList: List<Item>,
    duration: Int,
    addItem: () -> Unit
) {
    Column {
        itemList.forEach { item ->
	    AnimationListItem(item, duration)
        }
	// Card, Button etc...
        SomethingComposable(
            onClick = {
                addItem()
            }
        ) {
	    Text("add an item")
        }
    }
}
株式会社THIRD エンジニアブログ

Discussion