Creating a search bar in compose is a little bit complex but don’t worry here is the complete code breakdown
@Composable
fun InputField(
modifier: Modifier = Modifier,
valueState: MutableState<String>,
labelId: String,
enabled: Boolean,
isSingleLine: Boolean = true,
keyboardType: KeyboardType = KeyboardType.Text,
imeAction: ImeAction = ImeAction.Next,
onAction: KeyboardActions = KeyboardActions.Default
) {
OutlinedTextField(value = valueState.value,
onValueChange = { valueState.value = it},
label = { androidx.compose.material3.Text(text = labelId) },
singleLine = isSingleLine,
textStyle = TextStyle(fontSize = 18.sp,
color = MaterialTheme.colorScheme.background),
modifier = modifier
.padding(bottom = 10.dp, start = 10.dp, end = 10.dp)
.fillMaxWidth(),
enabled = enabled,
keyboardOptions = KeyboardOptions(keyboardType = keyboardType, imeAction = imeAction),
keyboardActions = onAction)
}
fun SearchForm(
modifier: Modifier = Modifier,
viewModel: BookListViewModel,
loading: Boolean = false,
hint: String = "Search",
onSearch: (String) -> Unit = {}
) {
Column {
val searchQueryState = rememberSaveable { mutableStateOf("") }
val keyboardController = LocalSoftwareKeyboardController.current
val valid = remember(searchQueryState.value) {
searchQueryState.value.trim().isNotEmpty()
}
InputField(valueState = searchQueryState,
labelId = "Search",
enabled = true,
onAction = KeyboardActions {
if (!valid) return@KeyboardActions
onSearch(searchQueryState.value.trim())
searchQueryState.value = ""
keyboardController?.hide()
})
}
}
SearchForm(
modifier = Modifier
.fillMaxWidth()
.padding(6.dp),
viewModel = viewModel
) { searchQuery ->
viewModel.searchBooks(query = searchQuery)
}