Jetpack Compose is a newer UI toolkit to build wonder screens on android native. This toolkit simplifies and accelerates UI development because it is 100% with Kotlin, reuses UI components, and has many powerful tools. One of the most remarkable tools is that you can preview your composables while you develop them.
When you are using previews it needs to have data for display in the design view. Sometimes the composable preview has a lot of data and you will have to write a huge code with a list of objects to populate the required data, that’s a lot of work, which is why many developers don’t have composable previews.
There is an easy way to centralize the data used in the composable previews and reuse it anywhere. You just need to use the PreviewParameterProvider interface provided by jetpack compose tools.
Let’s do an example. We have the following screen, but the data may be different depending on some application requirements, so we develop multiple previews respectively. We have a composable and many previews like this:
You have many previews because you want to see this composable with multiple data and if someone also needs this data, they will copy it, without reusing it. PreviewParameterProvider interface to the rescue…
Let’s look at a best practice for that. First, you need to create a data provider, like this:
The above data can be reused in any composable preview, then you can use the provider as a parameter in the preview, like so:
As a result, you can see multiple previews in the design view due to the values defined in the provider, like so:
I hope this information is useful for you and remember to share this blog post, your comment is always welcome.
Visit my social networks:
How to reuse data for previews in Jetpack Compose was originally published in Google Developers Experts on Medium, where people are continuing the conversation by highlighting and responding to this story.