I downloaded the demo project to study kotlin compose.
I try to add @Preview on a @Composable fun, but get warn that: Unresolved reference: Preview
I add implementation("androidx.compose.ui:ui-tooling-preview:1.1.1") in kotlin.sourceSets.named("CommonMain").dependencies in build.gradlw.kts:
named("commonMain") {
dependencies {
api(compose.runtime)
api(compose.foundation)
api(compose.material)
api(compose.materialIconsExtended)
implementation("androidx.compose.ui:ui-tooling-preview:1.1.1")
}
}
But still get Unresolved reference: Preview error.
I use IDEA 2021.3.3, Build #IU-213.7172.25, built on March 16, 2022.
You need to import androidx.compose.desktop.ui.tooling.preview.Preview to preview in desktop.
Go to Settings > Plugins > search in the marketplace for Compose Multiplatform IDE Support and Install this plugin.
After that, you can use Preview annotation and it will import the correct lib.
First of all, we need to understand that we are creating our composables or views into the commonMain into the shared module. So, we can’t specify to the IDE which platform we need to preview. This should be your folder structure.
|- sharedModule
|- androidMain
|- desktopMain
|- commonMain
|- composables
Then we need to create the previews into each platform we’ll need as following.
sourceSet we want to preview.val compose_version = "1.4.1"
val commonMain by getting {
dependencies {
// we don't need add anything in here
}
}
val desktopMain by getting {
dependencies {
implementation("org.jetbrains.compose.ui:ui-tooling-preview:${compose_version}")
}
}
val androidMain by getting {
dependencies {
implementation("org.jetbrains.compose.ui:ui-tooling-preview:${compose_version}")
}
}
Add your preview into the specific sourceSet module.
We imagine that we have a MyComposable view.
// commonMain/composables/MyComposable.kt
@Composable
fun MyComposable() {
Text(text = "Hello there!")
}
Now, we need to create our preview into the needed preview sourceSet platform module.
// androidMain/previews/MyComposablePreview.kt
@Composable
@Preview // now we are able to call the preview annotation
fun MyComposablePreview() {
MyComposable()
}
And we can add for desktop for example if needed.
// desktopMain/previews/MyComposablePreview.kt
@Composable
@Preview
fun MyComposablePreview() {
MyComposable()
}
Your files should look like this.
|- sharedModule
|- commonMain
|- composables
|- MyComposable.kt
|- desktopMain
|- previews
|- MyComposablePreview.kt
|- androidMain
|- previews
|- MyComposablePreview.kt
And that’s it! Hope it be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With