How can I update SearchBar results with every key ...
# compose
p
How can I update SearchBar results with every key pressed on the keyboard? there is no value and valuechanged variables on it. Here is the documentation and in the thread you can see the sample.
Copy code
@Composable
fun DockedSearchBarScaffold() {
    val textFieldState = rememberTextFieldState()
    val searchBarState = rememberSearchBarState()
    val scope = rememberCoroutineScope()
    val scrollBehavior = SearchBarDefaults.enterAlwaysSearchBarScrollBehavior()

    val inputField =
        @Composable {
            SearchBarDefaults.InputField(
                modifier = Modifier,
                searchBarState = searchBarState,
                textFieldState = textFieldState,
                onSearch = {
                    scope.launch {
                        searchBarState.animateToCollapsed()
                    }
                },
                placeholder = { Text("Search...") },
                leadingIcon = {
                    if (searchBarState.currentValue == SearchBarValue.Expanded) {
                        IconButton(
                            onClick = { scope.launch { searchBarState.animateToCollapsed() } }
                        ) {
                            Icon(Icons.AutoMirrored.Default.ArrowBack, contentDescription = "Back")
                        }
                    } else {
                        Icon(Icons.Default.Search, contentDescription = null)
                    }
                }
            )
        }

        TopSearchBar(
            scrollBehavior = scrollBehavior,
            state = searchBarState,
            inputField = inputField,
        )
        ExpandedDockedSearchBar(
            state = searchBarState,
            inputField = inputField,
        ) {
            SearchResults(
                busStops = emptyList(),
                onResultClick = { result ->
                    textFieldState.setTextAndPlaceCursorAtEnd(result)
                    scope.launch { searchBarState.animateToCollapsed() }
                }
            )
        }
}
z
The first sample in the docs for
TextFieldState
has an answer to your question: https://developer.android.com/reference/kotlin/androidx/compose/foundation/text/input/TextFieldState
p
I found that approach very advanced and complex
maybe is there any more simpler and traditional way?
z
That is the traditional way to use
TextFieldState
, as much as there is one. The value of the field is the
text
property on the state. It’s like a
mutableStateOf
. You use the same mechanisms to observe changes to it that you would for any compose state object.
If you want something like
onValueChanged
, just do
Copy code
LaunchedEffect(textFieldState) {
  snapshotFlow { textFieldState.text }
    .collect { onValueChanged(it) }
}