For one of the screens in our design we have to li...
# compose
t
For one of the screens in our design we have to limit the maximum width our content can take on the screen. From what I could tell,
widthIn(max = ...)
should have been able to solve this issue but it does not seem to behave as I expected. Does anyone have any experience using this modifier? More information in the 🧵
This snippet demonstrates the issue:
Copy code
@Preview(name = "Phone", device = Devices.PHONE)
@Preview(name = "Tablet", device = Devices.TABLET)
@Composable
private fun WidthInTestPreview() {
    MaterialTheme {
        Surface(
            color = Color.Black,
            modifier = Modifier.fillMaxSize()
        ) {
            Box(
                modifier = Modifier
                    .widthIn(max = 100.dp)
                    .height(100.dp)
                    .background(Color.DarkGray)
            )
        }
    }
}
This produces the following:
Both of these previews are quite a bit wider than the limit of 100.dp I've set in the snippet, but the Box still fills the whole width instead of just the 100.dp I've configured it to take (otherwise the black background would be visible)
s
Surface
inside itself uses a
Box
which has
propagateMinConstraints
to true. What this basically means, is that the child of
Surface
will always override the constraints that it has to match the current size of the Surface itself.
If you do
Copy code
private fun WidthInTestPreview() {
    MaterialTheme {
        Surface(
            color = Color.Black,
            modifier = Modifier.fillMaxSize()
        ) {
            Box {
                Box(
                    modifier = Modifier
                        .widthIn(max = 100.dp)
                        .height(100.dp)
                        .background(Color.DarkGray)
                )
            }
        }
    }
}
Then it’d work actually. Since the outer box would be the one with the max size, and then the rest of the children can have a lower minimum size if they want
t
Right, noticed that wrapping it in an extra box worked fine so that confused me even more 😅 . Thanks for the reply!
s
Yeap, it’s all because of
propagateMinConstraints
. Go in the box implementation and read the docs about it. After you know about it all these odd behaviors explain themselves if you see this is set to true