Home > Back-end >  Function body not being executed in Jetpack Compose
Function body not being executed in Jetpack Compose

Time:11-24

So I have the following composable function:

@Composable
fun SearchResult() {
    if (searchInput.isNotEmpty()) {
        Column() {
            Text("Search Result!")
        }
    }
}

Then I called the function from here:

private fun updateContent() {
    setContent {
        ChemistryAssistantTheme {
            // A surface container using the 'background' color from the theme
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colorScheme.background
            ) {
                Column() {
                    Title(" Chemistry Assistant ", " Made by Saket Tamrakar ")

                    Column() {
                        SearchElements()
                        SearchResult() // Here

                        //Options()
                    }
                }
            }
        }
    }
}

The issue here is that the function gets correctly called in the beginning, when I invoke updateContent() here:

OutlinedTextField(value = input, placeholder = { Text("Search for any element!") }, onValueChange = {
    input = it
    searchInput = it.text

    updateContent()
})

Control does reach the function (at least according to what the debugger tells me), but still fails to execute the function body.

Any ideas?

CodePudding user response:

You should keep searchInput as a state like:
val searchInput by mutableStateOf("")

This ensures that whenever the value of searchInput changes, any composable whose structure depends on it will also recompose(i.e recall the function).

Hope this solves your issue.

CodePudding user response:

Apparently moving the variable searchInput:

@Composable
fun SearchResult() {
    if (/*this one*/searchInput.isNotEmpty()) {
        Column() {
            Text("Search Result!")
        }
    }
}

..inside the MainActivity class fixed the issue.

  • Related