Reza Zeraati
Reza Zeraati

Reputation: 423

For Loop by Button onClick in Jetpack Compose?

How can we write a code that for example if user click a button, then 20 text or 20 of our function be created inside our Column below the Button?

Because we can't write the for loop inside the button click, because we get the: @Composable invocations can only happen from the context of a @Composable function Error

Upvotes: 0

Views: 977

Answers (1)

Thracian
Thracian

Reputation: 67403

If you add to mutableStateListOf, delete from it or update an item with new instance recomposition will be triggered and inside a for loop you can create Text for each data contained in SnapshotStateList.

@Composable
private fun AddComposablesInLoopSample() {
    val myList: SnapshotStateList<String> = remember {
        mutableStateListOf()
    }

    Column {
        Button(onClick = {
            myList.addAll(getData())
        }) {
            Text("Get Data")
        }

        myList.forEach {
            Text(it)
        }
    }
}

private fun getData(): List<String> {
    val myList = mutableListOf<String>()
    repeat(20) {
        myList.add("Row $it")
    }

    return myList.toList()
}

getData function is for demonstration to fill list.

Result

enter image description here

Upvotes: 2

Related Questions