How to reuse data for previews in Jetpack Compose

Juan Guillermo Gómez Torres
Google Developer Experts
2 min readAug 5, 2022

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:

Composable

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:

Building custom preview parameter provider

The above data can be reused in any composable preview, then you can use the provider as a parameter in the preview, like so:

Preview method using the provider as parameter

As a result, you can see multiple previews in the design view due to the values defined in the provider, like so:

Previews

--

--

Juan Guillermo Gómez Torres
Google Developer Experts

Tech Lead in Wordbox. @GDGCali Founder. @DevHackCali Founder. Firebase & GCPcloud & Kotlin & ODML @GoogleDevExpert . Android lover.