lvm12
lvm12

Reputation: 53

Composable doesn't recompose on state change

Why does this not recompose, despite state changing.

@Composable
fun IngredientsScreen() {

    var numberOfIngredients by remember {mutableStateOf(1)}

    Box(

    ){
        Column(
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.Start,
            modifier = Modifier
                .verticalScroll(rememberScrollState())
        ){
            for (i in 0 until numberOfIngredients){
                IngredientInputBox(
                    onClick = {
                        numberOfIngredients++
                    }
                )
            }
        }
    }
}

IngredientInputBox() is just a composable that contains a text field and a "+" symbol that is clickable, ideally when the symbol is pressed, a new text field would appear beneath it

@Composable
fun IngredientInputBox(
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var text by remember { mutableStateOf("") }

    Row(
        modifier = Modifier
            .padding(16.dp)
    ){
        TextField(
            value = text,
            onValueChange = { newText ->
                text = newText
            },
            label = {Text(text = stringResource(R.string.addNewIngredient))},
            modifier = Modifier
                .fillMaxWidth(0.3F)
                .weight(1f)
        )
        Text(
            text = "+",
            modifier = Modifier
                .clickable {onClick}
        )
    }
}

Upvotes: 0

Views: 71

Answers (1)

Tenfour04
Tenfour04

Reputation: 93834

Here's what's wrong with your implementation. This code:

modifier = Modifier
    .clickable {onClick}

Makes it so your button, when clicked, does absolutely nothing. The code in your lambda is what is called when the button is clicked, and it just declares the name of the click listener without doing anything with it.

You could fix it using

modifier = Modifier
    .clickable {onClick()}

or

modifier = Modifier
    .clickable(onClick = onClick)

Upvotes: 0

Related Questions