I'm trying to have a space between 2 composables i...
# compose
n
I'm trying to have a space between 2 composables in a
Column
with height of at most 16.dp, but should the incoming size constraint give less space, this element should shrink. How to do it without relying to a custom
Layout
? Even after 5 years of Compose, I still feel retarded using this framework. 😞 Code :
Copy code
Column {
    Card(modifier = Modifier.size(100.dp))
    Spacer(modifier = Modifier.background(Color.Gray).size(16.dp))
    Card(modifier = Modifier.size(50.dp))
}
Copy code
@Composable
private fun Card(modifier: Modifier = Modifier) {
    Column(modifier = modifier.background(Color.Yellow)) {
        Text("Foo")
        Box(
            modifier = Modifier
                .background(Color.Red)
                .fillMaxWidth()
                .weight(1F)
                .heightIn(0.dp, 16.dp)
        )
        Text("Bar")
    }
}
[1] is the actual result, [2] is the expected result
t
Copy code
Box(
    modifier = Modifier
        .background(Color.Red)
        .heightIn(max = 16.dp)
        .fillMaxSize()
)
Does this works?
n
No, height is not "compressed" when the incoming constraints are too small
image.png
t
You’re right! What about this:
Copy code
Box(
    modifier = Modifier
        .background(Color.Red)
        .heightIn(max = 16.dp)
        .weight(1f, fill = false)
        .fillMaxSize()
)
n
Yes !! The
fill
param out of nowhere lol, thank you
Without the .background to check its position, it can even be reduced to
Copy code
Spacer(
    modifier = Modifier
        .height(16.dp)
        .weight(1f, fill = false)
)
t
Even better 😄
n
In retrospective, what a weird way in compose to say
layout_weight=1
&
maxHeight=16dp
🤔
t
Honestly it’s weird that the
heightIn
has no effect over the
weight
z
I would re-order those modifiers to be
.weight(…).height(…)
, since
weight
is effectively always at the top of the modifier chain anyway since it directly communicates to the parent layout. It doesn't change the behavior, but it makes the modifiers read more like how they actually work.
All the
weight
modifier is doing in this case is changing the measure "priority" of the modified node. From the perspective of "weight", that's kind of a side effect, so i do kind of wish there was a more explicit way to say "all i care about is measure priority, i don't actually care about weighting". But it's the best we've got right now ¯\_(ツ)_/¯