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

Mark

11/15/2023, 5:24 AM
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

Ben Trengrove [G]

11/15/2023, 5:29 AM
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

Mark

11/15/2023, 5:33 AM
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

shikasd

11/15/2023, 11:32 AM
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.