How to use the @PreviewParameter annotation?
Asked Answered
A

2

22

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

Albi answered 25/2, 2021 at 19:20 Comment(1)
Just a warning: PreviewParameterProvider implementation must be public, otherwise preview will not display anything. Not even an error.Frauenfeld
S
22

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.

Symphonist answered 25/2, 2021 at 19:37 Comment(0)
L
11

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

Luting answered 4/6, 2021 at 4:8 Comment(3)
The link is no longer working - error 404.Stagemanage
If you need the full code I could update the answerLuting
Thanks for your response, but I have already found more information about preview providers :)Stagemanage

© 2022 - 2024 — McMap. All rights reserved.