Does anybody know where I can find out how to pass...
# compose
n
Does anybody know where I can find out how to pass a variable from one Composable to another?
j
A variable? Wym pass a variable? You are probably looking for state I think
n
Basically, I have a color that changes depending on which button is selected. I want to use that same color in another composable.
j
Well, you should have state in the lowest common parent of both child compose views, and then pass that down There should be some information about this in the tutorials, one sec
n
Thank you! 🙂
a
Composable functions are just functions, so if you need to pass-in a value just would call a (Composable) function passing in a parameter.
n
Yes, the problem is I can't because parameters only take val and not var.
a
Copy code
@Composable
fun Parent() {
    var color by remember { mutableStateOf(myColor) }
    ...
    Child(color)
}

@Composable
fun Child(color: Color) {
    ...
}
should work...
j
Tbh if you have nested childs, it would probably be smarter to pass down the color as a state. Otherwise, if you are using
by
, it implicitly calls the getValue delegate which will cause recomposition of the entire parent
By having the state passed down and not the value, it should only recompose the children I think, which is a bit more efficient
a
If you are using the state value on the parent as well, then that doesn't matter as it would need to recompose when value changes as well.
n
Thanks guys, I'll give this a try!
Hi again @jaqxues and @Archie. So if I understand correctly, my way of setting content in my Scaffold is not the recommended way? Instead I need to nest my Composables within each other?
Copy code
bodyContent = {
                ScrollableColumn(horizontalAlignment = CenterHorizontally) {
                    Spacer(modifier = Modifier.height(20.dp))
                    Text(text = "Quick Settings")
                    Spacer(modifier = Modifier.height(20.dp))
                    QuickOptions(context)
                    Spacer(modifier = Modifier.height(40.dp))
                    Text(text = "Sound Options")
                    Spacer(modifier = Modifier.height(20.dp))
                    SoundOptions()
                    Spacer(modifier = Modifier.height(30.dp))
                }
            },
a
The structure of your composables depends on your usecase. There is no right or wrong way of doing it.
👍 1
n
ok, I just can't work it out in spite of your kind help. I made a post in StackOverflow with more code. Maybe it makes more sense than my initial question?
a
For the question you posted, the first question you should be asking is where your
index
is coming from. Determining where the
index
is coming from would help you know what you should convert into a
State<T>
.