I don't think so, but you could do something like this
Copy code
val PreviewAmbient = ambientOf { false }
@Preview
@Composable
fun MainScreenPreview() {
Providers(PreviewAmbient provides true) {
MainScreen()
}
}
@Composable
fun MainScreen() {
val isInPreview = PreviewAmbient.current
...
}
s
salomonbrys
11/13/2020, 12:47 PM
That's what I currently do... But if I forget to provide the ambient in a preview, then I get "ViewModels creation is not supported in Preview" errors. So I'm looking for a more resilient way.
salomonbrys
11/13/2020, 12:51 PM
How about
Copy code
@Composable val isPreview: Boolean get() = ContextAmbient.current.applicationContext !is Application
?
j
Joost Klitsie
11/13/2020, 1:21 PM
I think the common way is to write your composables as to not have them rely on a system. So instead of:
Copy code
@Preview
@Composable
fun MainScreen() {
val viewModel by viewModels()// or however kids these days get their viewmodel
}
Copy code
@Composable
fun MainScreen() {
val viewModel by viewModels()
MainScreen(viewModel.viewState.collectAsState()) // Or pass in separate arguments
}
@Preview
@Composable
fun MainScreen(viewState: ViewState) {
// display things
}
Joost Klitsie
11/13/2020, 1:21 PM
This also makes your composables less platform specific
s
sindrenm
11/13/2020, 1:33 PM
I think you mixed up a couple of things in that last example?
@Preview
should probably be on the first composable, and its function name would need to be different. simple smile