Why the `Modifier.onSizeChange()` doesn't work in...
# compose
d
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
Did you try it on a device or an emulator?
a
I guess you need the interactive mode for the text to get updated.
d
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
You can enable it in settings.
d
oh thank you, I had missed that
z
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
What about that preview they were showing with an animated 3D content being previewed? is that gonna come later?
z
that relies on specific integrations with the animation primitives