Search

A search field that expands into a list of suggestions or results.

When to use

The app bar with search combines a search field with navigation icon and actions. When it expands, show suggestions or results either full screen or docked below the field.

Both variants share a SearchBarState and a TextFieldState, so the field, the expansion animation and the result list stay in sync.

Examples

Docked results

Focus the field and type.

val searchBarState = rememberSearchBarState()
val textFieldState = rememberTextFieldState()
val scope = rememberCoroutineScope()
val fruits = listOf("Apple", "Apricot", "Banana", "Blueberry", "Cherry", "Mango")
val results = fruits.filter { it.contains(textFieldState.text, ignoreCase = true) }

val inputField = @Composable {
    SearchBarDefaults.InputField(
        textFieldState = textFieldState,
        searchBarState = searchBarState,
        onSearch = { scope.launch { searchBarState.animateToCollapsed() } },
        placeholder = { Text("Search fruit") },
        leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
        trailingIcon = {
            if (textFieldState.text.isNotEmpty()) {
                IconButton(onClick = { textFieldState.clearText() }) {
                    Icon(Icons.Rounded.Close, contentDescription = "Clear")
                }
            }
        },
    )
}

Box(Modifier.fillMaxWidth().height(320.dp), contentAlignment = Alignment.TopCenter) {
    AppBarWithSearch(
        state = searchBarState,
        inputField = inputField,
    )
    ExpandedDockedSearchBar(state = searchBarState, inputField = inputField) {
        results.forEach { fruit ->
            ListItem(
                headlineContent = { Text(fruit) },
                modifier = Modifier.fillMaxWidth(),
            )
        }
    }
}

Parameters

NameTypeDefaultDescription
stateSearchBarStaterememberSearchBarState(). Animates between Collapsed and Expanded.
inputField@Composable () -> UnitUsually SearchBarDefaults.InputField.
navigationIcon / actions@ComposablenullAppBarWithSearch only.
content@Composable ColumnScope.() -> UnitSuggestions or results of the expanded bar.

Guidelines

Do:

Don't:

Accessibility

Related components