Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the modifier sizes not overwritten?

I have a composable function it assigns a size to a surface.

@Composable
private fun CreateImage(modifier: Modifier = Modifier) {
    Surface(
        modifier = modifier
            .size(150.dp)
            .padding(5.dp),
        shape = CircleShape,
        border = BorderStroke(1.dp, Color.LightGray)
    ) {
        Image(
            painter = painterResource(id = R.drawable.profile_image),
            contentDescription = "Profile Image",
            contentScale = ContentScale.Crop
        )
    }
}

When I call another method and change the size in the modifier parameter shouldn't it stick to 150dp.

If I call this method:

@Composable
private fun ChangeSize(name: String) {
    CreateImage(Modifier.size(100.dp))
}

It stays with the size 100dp even though in CreateImage I set it to 150dp. Why is the size not changing to 150dp and staying 100dp?

I thought it was supposed to change it to 150dp. Why is that not the case?

like image 764
AzureStar123 Avatar asked Oct 20 '25 04:10

AzureStar123


1 Answers

Modifier uses first size it got and it's a great feature when people don't provide any size to your Composable.

For instance

  CircleDisplay(
        modifier = circleModifier
            .widthIn(min = 70.dp)
            .heightIn(min = 70.dp),
        color = color
    )

if anyone doesn't provide any Modifier with any width or height instead of having 0 height and width you give a minimum size to your Composable. You can change this to max or exact size depending on your implementation. But when user modifier has some width height instead of yours the one provided by them is used thanks to using first size.

Default Composables like Slider also use this pattern, so without setting any dimension it has 48.dp height and fills max width of its parent.

BoxWithConstraint under Slider is as

    BoxWithConstraints(
        modifier
            .minimumTouchTargetSize()
            .requiredSizeIn(minWidth = ThumbRadius * 2, minHeight = ThumbRadius * 2)
            .sliderSemantics(value, tickFractions, enabled, onValueChange, valueRange, steps)
            .focusable(enabled, interactionSource)
    ) {
     // Rest of the Slider Implementation

}
like image 85
Thracian Avatar answered Oct 21 '25 19:10

Thracian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!