1

I need first item to be in focus when I enter the screen. I'm making a TV app

@Composable
fun TwoColumnGrid(
    animals: List<Animal>,
    onAnimalClicked: (Animal) -> Unit
) {
    val firstItemFocusRequester = remember { FocusRequester() }
    var twoColumnGridLoaded by remember { mutableStateOf(false) }

    MyTheme {
        LazyVerticalGrid(columns = GridCells.Fixed(2)) {
            items(animals) { animal ->
                val firstItemModifier = if (animals.isNotEmpty() && animal == animals[0]) {
                    Modifier.focusRequester(firstItemFocusRequester)
                } else {
                    Modifier
                }
                GridItem(
                    animal,
                    onClick = onAnimalClicked,
                    modifier = firstItemModifier
                )
            }
        }

       LaunchedEffect(Unit) {
            firstItemFocusRequester.requestFocus()

       }

    }
}

I get java.lang.IllegalStateException:

FocusRequester is not initialized. Here are some possible fixes:

Remember the FocusRequester: val focusRequester = remember { FocusRequester() }
Did you forget to add a Modifier.focusRequester() ?
Are you attempting to request focus during composition? Focus requests should be made in
response to some event. Eg Modifier.clickable { focusRequester.requestFocus() }
vighnesh153
  • 4,354
  • 2
  • 13
  • 27
  • Can you explain more the possible fixes and why they aren’t working? – ryankuck Aug 30 '23 at 13:32
  • That's what I get as an error message - IllegalStateException and this message: Remember the FocusRequester... so I don't know what other possible fixes are :/ I guess the problem is with recomposition but I don't know how to fix it – Katarina Zivkovic Aug 30 '23 at 14:04
  • I added an example that shows how to use the focus requester, please upvote if that answers the question or clarify where the problem still is! – ryankuck Aug 30 '23 at 14:15
  • 1
    But that's not what my problem is, on other screens it works well because I used it as the documentation says. The problem is, I need to put it on the first item in LazyVerticalGrid – Katarina Zivkovic Aug 30 '23 at 16:55
  • Ok I tried a new answer - let me know if that answers it – ryankuck Aug 30 '23 at 18:06
  • Does this answer your question? [How to always focus on the first item while focussing on a TVLazyRow?](https://stackoverflow.com/questions/76880923/how-to-always-focus-on-the-first-item-while-focussing-on-a-tvlazyrow) – vighnesh153 Sep 01 '23 at 03:41
  • Remember that using focus requester in a `LaunchedEffect` is not safe because the code inside in is run in a coroutine scope. So, it is not guaranteed that focusRequester will be initialized before running LaunchedEffect. – vighnesh153 Sep 01 '23 at 03:47
  • Does this help: https://stackoverflow.com/questions/76842673/focus-restoration-on-navigation-popbackstack-and-focus-restoration-using-state-m? – vighnesh153 Sep 01 '23 at 03:48

0 Answers0