Hello! Small doubt I’m creating a button componen...
# compose
r
Hello! Small doubt I’m creating a button component and it should be small (it should ony grow as much as it needs). Therefore
fillMaxWidth
modifier should not be an option nor should be allowed. I still give the chance to the developer to pass a
Modifier
to the button, so it opens the door for him to apply that
fillMaxWidth
. Does anyone know if there’s a way to force a button to use
wrapContentWidth
or “_remove_”
fillMaxWidth
option?
s
You can apply a
wrapContentWidth
after you apply the modifier incoming to your composable. It would make for some super weird debugging sessions though if you forget that you’ve done that 😄
r
I thought the same, I was thinking about the “_modifier order matters_” phrase but doesn’t seem to work. Example:
Copy code
@Composable
fun ButtonSmall(
    modifier: Modifier = Modifier,
    text: String,
) {
    Box(
        modifier.border(1.dp, Color.Black).wrapContentWidth(),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "text")
    }
}
By using it
ButtonSmall(Modifier.fillMaxWidth(), text)
It still applies
fillMaxWidth
modifier because border fills the entire width. I’ve also tried to set the border after
wrapContentWidth()
Modifier but doesn’t seem to make an effect
s
Just did this
Copy code
Box(Modifier.size(200.dp).border(1.dp, Color.Red)) {
    SmallButton(Modifier.fillMaxWidth())
}
And then
Copy code
@Composable
fun SmallButton(modifier: Modifier = Modifier) {
    Box(
        modifier.wrapContentWidth(Alignment.Start).width(80.dp).height(40.dp).border(1.dp, Color.Blue),
    ) {
        Text("H")
    }
}
And this gives this output
Well for sure if you put the border before the wrap, then it will definitely go on the bounds it gets after the fillMaxWidth.
Doing
Copy code
Box(Modifier.size(200.dp).border(1.dp, Color.Red)) {
    ButtonSmall(Modifier.fillMaxWidth(), "H")
}
and
Copy code
@Composable
fun ButtonSmall(
    modifier: Modifier = Modifier,
    text: String,
) {
    Box(
        modifier.wrapContentWidth().border(1.dp, Color.Black),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "text")
    }
}
Does indeed also wrap the content width
r
Ah, you’re right
s
You just need to specify in the
wrapContentWidth
after you’ve wrapped, where do you want the content to be aligned
If you change it to
wrapContentWidth(Alignment.Start)
it will output this
r
I somehow mixed it up between multiple small components I was using to test the behaviour, it definitely works
Thank you so much 🙏 🫶
s
Awesome, good luck with it 🤗