The Coding Fox
The Coding Fox

Reputation: 1585

Function body not being executed in Jetpack Compose

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?

Upvotes: 0

Views: 397

Answers (2)

Hyzam
Hyzam

Reputation: 173

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.

Upvotes: 1

The Coding Fox
The Coding Fox

Reputation: 1585

Apparently moving the variable searchInput:

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

..inside the MainActivity class fixed the issue.

Upvotes: 0

Related Questions