I am trying to get a preview of a composable which takes one String parameter as input. I am not sure how the @PreviewParameter
annotation is supposed to be used.
This is was I tried
class DogProvider : PreviewParameterProvider<String> {
override val values = listOf("Bela", "Stalone").asSequence()
}
@PreviewParameter(DogProvider::class)
@Composable
fun OverviewCard(
dog: String,
modifier: Modifier = Modifier
) {
Text(dog)
}
No preview is rendered. If I also add the @Preview
annotation it says that I should use @PreviewParameter
You are very close, but the @PreviewParameter
should be applied your Composable's parameters, not the function itself.
Your example should look like this:
@Preview
@Composable
fun OverviewCardPreview(
@PreviewParameter(DogProvider::class) dog: String,
) {
Text(dog)
}
Also note that you can currently only have a single @PreviewParameter
-annotated property for each previewed composable.
Since the Jetpack-Compose API tells us:
Multiple @PreviewParameter are not allowed
So the best thing to do to avoid having to initialize parameters by default if we have more than one, is to wrap all the parameters in a data class and mock them in the implementation of PreviewParameterProvider
@Preview
@Composable
private fun FeatureScreenPreviewMock(
@PreviewParameter(FeatureScreenPreviewParamProvider::class) featureScreenParams: FeatureScreenParams,
)
class FeatureScreenPreviewParamProvider : PreviewParameterProvider<FeatureScreenParams>
In this way we are not limited to the number of parameters
Sample with WelcomeScreenPreviewMock
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With