Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the @PreviewParameter annotation?

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

like image 440
Henning Avatar asked Sep 11 '25 22:09

Henning


2 Answers

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.

like image 148
Bryan Herbst Avatar answered Sep 13 '25 14:09

Bryan Herbst


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

like image 26
Braian Coronel Avatar answered Sep 13 '25 15:09

Braian Coronel