How can I give different id(or key?) for different...
# compose
c
How can I give different id(or key?) for different compose function in this case?
Copy code
@Comopsable
fun SomeScreen(
    data: MyData,
    layoutType: LayoutType
    onChangeLayoutField: () -> Unit
){
    Row{
        when(layoutType){
            is AType -> ALayout(data)
            is BType -> BLayout(data)
        }
        Button(
            onClick = onChangeLayoutField
        )
    }
}

@Composable
fun ALayout(
    choiceList: List<Choice>,
    modifier: Modifier = Modifier
) {
    var selectedIndex by rememberSaveable { mutableStateOf(-1) }

    LazyColumn(
        verticalArrangement = Arrangement.spacedBy(6.dp),
        modifier = modifier
    ) {
        items(choiceList.size) { columnIndex ->
            val choice = choiceList[columnIndex]

            SingleSelectionButton(
                index = columnIndex,
                text = choice.label ?: "",
                isChecked = selectedIndex == columnIndex,
                fontSize = 13.sp,
                fontColor = Color.Gray002,
                onNotifyButtonState = { index, isChecked ->
                    selectedIndex = index
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
            )
        }
    }
}
here's the sample code. I'd like to clear SomeLayout when the next layout after the button is clicked. What I expected here is. When ALayout's data(from param) changes, the view clears when it recomposes. But, It isn't. For example, 1. ALayout(dataA) -> ALayout(dataB) -> ALayout(dataC): SingleSelectionButton's isChecked state still remains. So, Let's say O is isChecked = true, and X is false. In ALayout, I made it X O X X, then click next button, then, X O X X state is still there, even last ALayout is still X O X X. 2. However, when there's other Layout which is BLayout here. It clears the previous ALayout state and works normal. For instance, ALayout(dataA) -> BLayout(dataB) -> ALayout(dataC). BLayout clears previous ALayout state so, new ALayout after BLayout shows X X X X which is correct.
j
I answered on StackOverflow, but I think passing
choiceList
as a key to
rememberSaveable
will do what you want.
Copy code
var selectedIndex by rememberSaveable(choiceList) { mutableStateOf(-1) }
Without the key the value of selectedIndex is remembered across compositions which is what remember is supposed to do. So you need to signal to rememberSaveable that you want it to calculate it’s value again in some way. This is what the key does.