I have the following code piece:
@Composable
fun SearchScreen(
snackbarHostState: SnackbarHostState,
navController: NavHostController,
viewModel: SearchViewModel = koinViewModel()
) {
val uiState: SearchUiState by viewModel.uiState.collectAsStateWithLifecycle()
...
LaunchedEffect(uiState.errorMessageId) {
uiState.errorMessageId?.let { errorMessageId ->
snackbarHostState.showSnackbar(
message = stringResource(id = errorMessageId),
duration = SnackbarDuration.Short
)
}
}
}
data class SearchUiState(
...
@StringRes val errorMessageId: Int? = null
)
I get the following boring error for the stringResource call:
@Composable invocations can only happen from the context of a @Composable function
How can I overcome this problem?
You are getting the error because the showSnackBar method is not a Composable and the usage of stringResource is a Composable.
To overcome this, you can either acquire your string resource inside one of your Composables and pass it to the showSnackBar method and assign it to the message.
Or, you can go the other route and get a context and do the following:
val context = LocalContext.current
context.resources.getString(R.string.errorMesageId)