Home > Blockchain >  For Loop by Button onClick in Jetpack Compose?
For Loop by Button onClick in Jetpack Compose?

Time:09-27

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

CodePudding user response:

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

  • Related