0

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

2
  • Do you wish to create 20 Composables below Button when you click it once? Commented Sep 25, 2022 at 18:36
  • yeah. a Text for example. in fact, I want to make a Text for each record that I have in my SQLite Commented Sep 25, 2022 at 18:42

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.