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

Lukasz Burcon

02/07/2022, 9:16 PM
Hey, have you ever had any problems or weird behaviours when chaining modifiers? I’m passing
Modifier.requiredSize(50.dp)
to
MyTestComposable
, and I expected that I would override the size with the new value -
50.dp
. And yeah, the size is being modified, but somehow when I try to use
MyTestComposable
in a Column it looks like another view is being drawn on top of
MyTestComposable
- take a look at the picture attached in thread.
Copy code
@Composable
private fun MyTestComposable(
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = Modifier
            .border(1.dp, Color.Blue)
            .requiredSize(25.dp)
            .then(modifier)        ,
    )
}
For the code presented below I get totally unexpected output (look at the image). Any ideas what’s happening there?
Copy code
Column {
    MyTestComposable(
          modifier = Modifier
              .requiredSize(50.dp)
              .border(1.dp, Color.Red),
    )
    Text(text = "Test text")
}
Looks like the most “left” size modifier (25.dp in that case) is being applied to calculate view’s position in the Column and then Text uses those coordinates to be placed in the layout. Is that expected behaviour?
m

mattinger

02/07/2022, 10:13 PM
Modifiers are "chained", not "overriden". So what's happening is when it's rendered, it's first applying the outer modifier, which is:
.requiredSize(50.dp).border(1.dp, Color.red)
then it's applying the second one:
.requiredSize(25.dp).border(1.dp, Color.Blue)
this effectively shrinks the bounds of the view down to 25, but the red border is still drawn because you haven't applied any clipping to it. As such, your text is then layed out right underneath the view, which happens to now be 25.dp
Modifier order matters, and when you combine the same modifier, it especially causes some confusion. I won't call this a mistake, but i see this happen to people quite often and they don't understand why. It's not all that dissimilar from something like this which ends with a blue background and then inset 10 dp on all sides is a red background.
Copy code
Column(modifier=
    Modifier.background(Color.Blue)
            .padding(10.dp)
            .background(Color.Red)
)
l

Lukasz Burcon

02/08/2022, 7:40 AM
Yeah, I thought it’s similar to the case you mentioned. I wonder if we should declare sizes in reusable components accepting modifiers, as my example clearly shows it can lead to problems
4 Views