In the latest version of Jetpack Compose (1.3.3 for now), if you use this:
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
trying to auto focus a TextField
, you would get:
java.lang.IllegalStateException:
FocusRequester is not initialized. Here are some possible fixes:
1. Remember the FocusRequester: val focusRequester = remember { FocusRequester() }
2. Did you forget to add a Modifier.focusRequester() ?
3. Are you attempting to request focus during composition? Focus requests should be made in
response to some event. Eg Modifier.clickable { focusRequester.requestFocus() }
Here is an elegant solution without using delay
:
val focusRequester = remember { FocusRequester() }
var textFieldLoaded by remember { mutableStateOf(false) }
TextField(
modifier = Modifier
.focusRequester(focusRequester)
.onGloballyPositioned {
if (!textFieldLoaded) {
focusRequester.requestFocus() // IMPORTANT
textFieldLoaded = ture // stop cyclic recompositions
}
},
value = someValue,
onValueChange = {
// ...
}
)
// We don't need this
// LaunchedEffect(Unit) {
// focusRequester.requestFocus()
// }