Jetpack Compose Preview — Complete Guide
In this tutorial, you'll learn about Jetpack Compose Preview. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your @Preview shows a blank screen, crashes with DefaultPreviewFactory, or doesn't reflect the actual runtime state.
Wrong Approach ❌
// Preview with no parameters — shows empty/default state only
@Preview(showBackground = true)
@Composable
fun BadPreview() {
// This composable requires a ViewModel parameter
UserProfileScreen(viewModel = ViewModel()) // NPE!
}
// Single preview for all screen sizes
@Preview
@Composable
fun PhonePreview() {
// Tested only on one phone size
MyComposable()
}
Output: Preview crashes due to missing dependencies. No multi-device testing.
Right Approach ✅
// Multiple previews for different configurations
@Preview(
name = "Phone",
device = Devices.PHONE,
showBackground = true,
showSystemUi = true
)
@Preview(
name = "Tablet",
device = Devices.TABLET,
showBackground = true
)
@Preview(
name = "Dark Mode",
uiMode = Configuration.UI_MODE_NIGHT_YES
)
@Composable
fun MyComposablePreview() {
// Use a preview-safe approach
DodaTechTheme {
Surface {
MyComposable(
title = "Preview Title",
subtitle = "This renders in the IDE"
)
}
}
}
// For ViewModel-dependent composables, use a wrapper
@Composable
fun MyComposablePreview() {
DodaTechTheme {
MyComposable(
state = UiState.Success("Preview data"),
onAction = {}
)
}
}
Output: Multiple preview variants rendering correctly across devices and themes.
Prevention
- Decouple UI from ViewModel — accept plain state in composables.
- Create wrapper preview composables with dummy data.
- Use
@Previewwithdevice,uiMode, andfontScaleparameters. - Always wrap previews in your app's
Theme.
Common Mistakes with compose preview
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro