How to request focus on first item in LazyColumn/LazyVerticalGrid? (Jetpack compose)

895 Views Asked by At

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() }
0

There are 0 best solutions below