yazan sayed
yazan sayed

Reputation: 1139

Android Compose: can composables store more than a single state?

from the official docs (Managing State)

Composable functions can store a single object in memory by using the remember composable. A value computed by remember is stored in the composition during initial composition, and that stored value is returned during recomposition. You can use remember to store both mutable and immutable objects.

so a single remember per composable, but I've found code online that used more than a single state in a composable, actually from an official source :DropdownMenu

@Composable
fun DropdownDemo() {
    var expanded by remember { mutableStateOf(false) }
    var selectedIndex by remember { mutableStateOf(0) }
    val items = listOf("A", "B", "C", "D", "E", "F")
    val disabledValue = "B"
    Box(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) {
        Text(items[selectedIndex],modifier = Modifier.fillMaxWidth().clickable(onClick = { expanded = true }).background(
            Color.Gray))
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier.fillMaxWidth().background(
                Color.Red)
        ) {
            items.forEachIndexed { index, s ->
                DropdownMenuItem(onClick = {
                    selectedIndex = index
                    expanded = false
                }) {
                    val disabledText = if (s == disabledValue) {
                        " (Disabled)"
                    } else {
                        ""
                    }
                    Text(text = s + disabledText)
                }
            }
        }
    }
}

the code works fine, but it stores two states, doesn't it ?!

Upvotes: 1

Views: 805

Answers (1)

Lejdi
Lejdi

Reputation: 23

I assume that documentation meant, that using one remember you can store one object, not that each composable can't have multiple remember values.

Upvotes: 2

Related Questions