KamilH
10/24/2024, 9:50 AMModifier
that, under the hood, uses onGloballyPositioned
and saves the y
value in the map with the corresponding enum value (code in Thread).
Is there a better way to achieve that? Do you see any issues with this solution?KamilH
10/24/2024, 9:50 AM@Composable
fun <T: Enum<*>> ScrollToContainer(
scrollState: ScrollState,
scrollTo: T?,
onScrolledTo: (T) -> Unit,
content: @Composable ScrollToContainerScope<T>.() -> Unit,
) {
val map = remember { mutableStateMapOf<T, Int>() }
val scope = remember { ScrollToContainerScope(map) }
LaunchedEffect(key1 = scrollTo) {
if (scrollTo != null) {
val position = map[scrollTo]
if (position != null) {
scrollState.animateScrollTo(position)
onScrolledTo(scrollTo)
} else {
error("tag not found: $scrollTo")
}
}
}
content(scope)
}
class ScrollToContainerScope<T: Enum<*>>(private val map: MutableMap<T, Int>) {
fun Modifier.markWithTag(tag: T): Modifier =
onGloballyPositioned {
map[tag] = it.positionInParent().y.toInt()
}
}
Albert Chang
10/24/2024, 10:00 AMKamilH
10/24/2024, 10:27 AM