Assuming the parent width is 200
.
When I run this initially, it prints:
current maxWidth: 200
I then increase the parent width to 600
and after recomposition it prints:
current maxWidth: 600
After I tap on the Box the local function onTap
is called and it prints the old value:
onTap maxWidth: 200
What happens is that onTap
captures the constraints.maxWidth
value and it doesn't update it later. Any way to get the current value inside onTap
?
BoxWithConstraints(
propagateMinConstraints = true,
modifier = Modifier
.background(Color.Green)
.fillMaxSize()
) {
println("current maxWidth: ${constraints.maxWidth}")
fun onTap(position: Offset) {
println("onTap maxWidth: ${constraints.maxWidth}")
}
Box(
modifier = Modifier
.background(Color.Blue)
.pointerInput(Unit) {
detectTapGestures(onTap = ::onTap)
}
) {
}
}
CodePudding user response:
pointerInput
captures current scope. You can experience same behavior with some other Compose function, like remember
, LaunchedEffect
, etc: all of them have vararg key
parameter.
To make it update the scope, you can pass any values on which your calculation depends to key
, in your case:
.pointerInput(constraints.maxWidth) {
detectTapGestures(onTap = ::onTap)
}