How can I add a good looking fling behaviour to th...
# compose
s
How can I add a good looking fling behaviour to the red rect? All I see is the velocity tracker returning nonsense values (most of the times) - what am I missing?
Copy code
val coroutineScope = rememberCoroutineScope()
val offsetX = remember { Animatable(0f) }

BoxWithConstraints(
    modifier = Modifier
        .fillMaxSize()
) {
    Box(
        modifier = Modifier
            .offset { IntOffset(offsetX.value.roundToInt(), 0) }
            .fillMaxHeight()
            .width(50.dp)
            .background(Color.Red)
            .pointerInput(Unit) {
                val velocityTracker = VelocityTracker()
                val decay = splineBasedDecay<Float>(this)

                offsetX.updateBounds(0f, constraints.maxWidth - 50.dp.toPx())

                detectHorizontalDragGestures(
                    onHorizontalDrag = { change, dragAmount ->
                        coroutineScope.launch { offsetX.snapTo(offsetX.value + dragAmount) }
                        velocityTracker.addPointerInputChange(change)
                    },
                    onDragEnd = {
                        val velocity = velocityTracker.calculateVelocity().x
                        velocityTracker.resetTracking()

                        val target = decay.calculateTargetValue(offsetX.value, velocity)

                        coroutineScope.launch {
                            offsetX.animateTo(target, initialVelocity = velocity)
                        }
                    }
                )
            }
    )
}
a
You can steal the swipeable impl from material
s
I believe the problem is the velocity is not calculated correctly when
pointerInput
is targeted by
offset
. If I move the
pointerInput
to the upper composable, there are no issues - however this will make the rect draggable by anywhere, which is not what I want