Why is the first `Text` showing the updated text, ...
# compose
m
Why is the first
Text
showing the updated text, but not the second
Text
?
Copy code
@Preview(showBackground = true)
@Composable
fun WithConstraintsComposable() {
    var text: String by remember {
        mutableStateOf("not set")
    }
    Column {
        BoxWithConstraints {
            text = "My minHeight is $minHeight while my maxWidth is $maxWidth"
            Text(text, modifier = Modifier.background(Color.Green))
        }
        Text(text, modifier = Modifier.background(Color.Red))
    }
}
b
You shouldn't write to state inline in Compose like that where you do
text =
, this is actually probably a backwards write because BoxWithConstraints is a subcompose layout and so runs after the bottom text. https://developer.android.com/jetpack/compose/performance/bestpractices#avoid-backwards
👆 1
mind blown 1
👆🏾 1
In general, state should always be mutated outside of composition. Which in practice normally means as part of an event lambda like onClick or something
thank you color 2
m
Thanks Ben, that makes sense. My motivation here was to grab some metric from the first item in the column so that it could be used by the second item. I want to do something quite simple: Make sure the second item in the column is no wider that the first item.
s
Technically, the original example should work, albeit it is not recommended to write to a state from composition. It should update, maybe with a little delay but still.