Home > database >  Can't read the current constraints in Compose local function
Can't read the current constraints in Compose local function

Time:11-22

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. To make it update the scope, you can pass any values on which your calculation depends to key, in this case:

.pointerInput(constraints.maxWidth) {
    detectTapGestures(onTap = ::onTap)
}
  • Related