I have a TextField
for a search query and a Button
that will execute the search and the results are shown in a column. Since the search takes a few seconds to run I want it to be executed on button press and not on text change.
Here is a simplified demonstration:
Column {
val list = remember { mutableStateListOf<String>() }
val textFieldValue = remember { mutableStateOf(TextFieldValue("")) }
TextField(
value = textFieldValue.value,
onValueChange = { textFieldValue.value = it }
)
Button({
list.clear()
list.addAll(textFieldValue.value.text.split(""))
}) {
Text("Search")
}
list.forEach {
println("test")
Text(it)
}
}
After the first time that the button is pressed, the foreach loop will run on text change. Even clicking on the TextField
will rerun the loop. This doesn't run the search on text change, but re-renders the results and that causes glitches while typing in the text field.
How can this be prevented?
remember
does not inherently cause anything to happen, and the location of theremember
call is not important. You could, if you liked, set uptextFieldValue
and pass it toTextAndButton
, and it would still work properly. – Langlauf