I have a screen with TextFields
. I need the first TextField
to be automatically focused when the screen is displayed.
Minified Example code
@Composable
fun ScreenView(
data: ScreenViewData,
) {
val focusManager = LocalFocusManager.current
val focusRequester = remember {
FocusRequester()
}
LaunchedEffect(
key1 = Unit,
) {
focusRequester.requestFocus()
}
Scaffold() { innerPadding ->
Column {
OutlinedTextField(
modifier = Modifier.focusRequester(focusRequester),
)
}
}
}
The code works without any issues.
But, in compose UI testing I am getting the following error.
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() }
Test code
@ExperimentalAnimationApi
class ScreenViewTest {
@get:Rule
val composeTestRule = createComposeRule()
@ExperimentalMaterialApi
@Test
fun ScreenViewElementsAreDisplayed() {
composeTestRule.setContent {
MyAppTheme {
ScreenView(
data = ScreenViewData(),
)
}
}
// Test fails before reaching assert statements
}
}