Skip to main content
Donovan LaDuke - Developer

Using Lists in Compose Previews


Featured in Android Weekly Issue 628 As Seen In - jetc.dev Newsletter Issue #220

When making a Compose component there are scenarios where it is helpful to preview several variations of the component. At the start, just creating separate preview functions for each can work just fine, but as the number of previews grows this becomes unmaintainable. A solution for this is presented in the documentation using PreviewParameterProvider which can be found here. This solution works, but using a List is far more common than using a Sequence. Thankfully there is a built-in implementation for this that doesn't require calling asSequence on the List.

Enter CollectionPreviewParameterProvider #

The CollectionPreviewParameterProvider implementation of PreviewParameterProvider is a class that takes a single parameter of Collection<T> which is a supertype of List, this means the list can be passed directly in, no conversion necessary. Then inside the class is converted to a Sequence without the implementer ever having to think about it. Here is the example from the documentation updated to use a CollectionPreviewParameterProvider.

class UserPreviewParameterProvider 
  : CollectionPreviewParameterProvider<User>(
  collection = listOf(
    User("Elise"),
    User("Frank"),
    User("Julia")
  )
)

@Preview
@Composable
fun UserProfilePreview(
  @PreviewParameter(UserPreviewParameterProvider::class) 
  user: User
) {
  UserProfile(user)
}

Conclusion #

With this simple change using an existing list of dummy data becomes trivial and will work the same as PreviewParameterProvider in most cases. To learn more about approaches to previewing composables check out my article here. Until next time, thanks!

Did you find this content helpful?

Please share this post and be sure to subscribe to the RSS feed to be notified of all future articles!

Want to go above and beyond? Help me out by sending me $1 on Ko-fi. It goes a long way in helping run this site and keeping it advertisement free. Thank you in advance!

Buy me a Coffee on Ko-fi