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

sindrenm

02/09/2023, 11:23 AM
I find `Surface`'s behaviour a little inconsistent from other containers, because it implicitly makes a
Box(propagateMinConstraints = true)
. I would expect the following to show a
Surface
with no color at all, because I haven't set any size for the
Spacer
inside it, but instead, the
Spacer
fills the entire
Surface
with its green color, as per the picture.
Copy code
@Preview
@Composable
fun SurfaceBehaviour() {
    Surface(Modifier.padding(16.dp).fillMaxWidth().aspectRatio(16f / 9f)) {
        Spacer(Modifier.background(Color.Green))
    }
}
This doesn't really seem documented, either, so I'm curious as to why
Surface
would behave like this.
Just noticed that
@Preview(widthDp = 50)
also propagates that width to the root child, which is also something I wouldn't expect.
Copy code
@Preview("500 dp width", widthDp = 500)
@Preview("400 dp width", widthDp = 400)
@Preview("350 dp width", widthDp = 350)
@Composable
private fun Preview2() {
    Spacer(Modifier.height(50.dp).background(Color.Magenta))
}
l

Louis Pullen-Freilich [G]

02/09/2023, 2:27 PM
Surface behaves more like a decorator container for its child, the idea is that you can put it around your layout container instead of needing a SurfaceRow, SurfaceColumn, etc
s

sindrenm

02/09/2023, 2:31 PM
Right. And I can maybe kinda see that, although it breaks my expectations of where modifiers are applied, still. And it also means that e.g. Card inherits the same functionality, which I definitely wouldn't expect.
l

Louis Pullen-Freilich [G]

02/09/2023, 2:33 PM
Maybe it’s helpful to treat surface / card as a complex set of modifiers, in the same way you would add modifiers to a row or a column, you’re just decorating that layout with a surface / card.
s

sindrenm

02/09/2023, 2:36 PM
I guess, but that's not obvious from the docs, IMO. In that case, would it make more sense to have a (public)
Modifier.surface
, for consistency? I'm mostly just asking because it made my own custom layout behave differently when it was wrapped in a Box vs. a Surface, which is something I wouldn't expect initially.
I solved my issue by wrapping my
Layout
in a
Box
, but it felt a little weird.
l

Louis Pullen-Freilich [G]

02/09/2023, 2:38 PM
We investigated that a while ago, but a) there are some technical limitations because of the things that surface needs to handle (content color propagation for example), and also there is some benefit to having a semantic Surface / Card in the hierarchy - it’s a standalone concept that maps to Material guidance. Maybe worth filing a bug to expand the documentation for layout expectations a bit more here
s

sindrenm

02/09/2023, 2:40 PM
Oh yeah, that makes sense. 👍 I can look into filing a request for expanding the docs a bit when I'm back at the office tomorrow. Thanks for explaining! 🙂
4 Views