So I have an app for both mobile and TV and on firebase I got error on crashlytics - Fatal Exception: 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() }. I don't know what I'm doing wrong
val buttonFocusRequester = remember { FocusRequester() }
var isItemInFocus by remember { mutableStateOf(false) }
Surface(
modifier = modifier,
color = MaterialTheme.colorScheme.primary,
) {
val tvModifier =
if (isTV) {
Modifier
.onFocusChanged { isItemInFocus = it.isFocused }
.focusRequester(buttonFocusRequester)
} else {
Modifier
}
LaunchedEffect(Unit) {
if(isTV) {
buttonFocusRequester.requestFocus()
}
}
LaunchedEffect
might run before the item has a chance to be placed on the screen. You can have a boolean flag that tracks whether the button is placed and then request focus.
var isPlaced by remember { mutableStateOf(false) }
val tvModifier =
if (isTV) {
Modifier
.onPlaced { isPlaced = true }
.focusRequester(buttonFocusRequester)
} else {
Modifier
}
LaunchedEffect(isPlaced) {
if(isTV && isPlaced) {
buttonFocusRequester.requestFocus()
}
}