https://kotlinlang.org logo
#compose
Title
# compose
d

Daniele Segato

07/08/2021, 9:37 AM
Why the
Modifier.onSizeChange()
doesn't work in Preview?
Copy code
var cardSize by remember { mutableStateOf<IntSize?>(null) }
    Box(
        modifier = Modifier
            .background(Color.White)
            .aspectRatio(1f)
            .fillMaxSize()
            .onSizeChanged { cardSize = it }
    ) {
        Text(text = "Size is = $cardSize")
    }
the preview always show "Size is null" while if I run it I get the size as I expect? Is there a way to fix the preview?
In my case I can encapsulate in a BoxWithConstraint and use the
maxWidth
but this is kind of weird
m

ms

07/08/2021, 9:43 AM
Did you try it on a device or an emulator?
a

Albert Chang

07/08/2021, 9:48 AM
I guess you need the interactive mode for the text to get updated.
d

Daniele Segato

07/08/2021, 10:25 AM
yes in both emulator and device work as expected.
I guess you need the interactive mode for the text to get updated.
I think it's disabled in AS Beta
a

Albert Chang

07/08/2021, 10:35 AM
You can enable it in settings.
d

Daniele Segato

07/08/2021, 1:06 PM
oh thank you, I had missed that
z

Zach Klippenstein (he/him) [MOD]

07/08/2021, 2:35 PM
The reason is because the preview only runs a single composition. The size changed event isn’t sent until after the first composition-layout completes, which would normally trigger a recomposition but not in previews. This means if you’re using that state in the composition (as you are) then it will probably flicker in even on a real device because that first frame will be drawn without the size value.
BoxWithConstraints
might be a better approach if it works for your use case since it gives you the constraints immediately, on the first composition. No missed frame, no flicker
d

Daniele Segato

07/08/2021, 6:30 PM
What about that preview they were showing with an animated 3D content being previewed? is that gonna come later?
z

Zach Klippenstein (he/him) [MOD]

07/08/2021, 6:34 PM
that relies on specific integrations with the animation primitives
9 Views