Updating a Composable Function with a Lambda

Issue

In the Android developer docs at the following web address: https://developer.android.com/jetpack/compose/mental-model#recomposition

There is a composable function which is given as the following:

@Composable
fun ClickCounter(clicks: Int, onClick: () -> Unit) {
    Button(onClick = onClick) {
        Text("I've been clicked $clicks times")
    }
}

It’s said in the text that this produces an element which updates the number of times its been clicked every time it is clicked. However, looking at it, it seems to need a lambda function to do that.

When I try and put it into the SetContent function I get the following:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            WorkTimerTheme {
                Conversation(SampleData.conversationSample)
                ClickCounter(clicks = 0) {
                    //Insert My Function Here
                }
            }
        }
    }
}

The comment //Insert My Function Here has been added by me. I presume that within this I have to put a Lambda which updates the clicks value of the composable, but I have no idea what to put. Does anyone know an acceptable way of writing this?

Solution

You need a MutableState to trigger recomposition and remember{} to keep previous value when recomposition occurred.

I asked a question about it and my question contains answer to your question.

@Composable
fun MyScreenContent(names: List<String> = listOf("Android", "there")) {
    val counterState = remember { mutableStateOf(0) }

    Column(modifier = Modifier.fillMaxHeight()) {

        Counter(
            count = counterState.value,
            updateCount = { newCount ->
                counterState.value = newCount
            }
        )
    }
}


@Composable
fun Counter(count: Int, updateCount: (Int) -> Unit) {
    Button(
        onClick = { updateCount(count + 1) },

    ) {
        Text("I've been clicked $count times")
    }
}

Answered By – Thracian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published